首页  >  问答  >  正文

如何调整Sequence(Laravel 8)中创建的对象数量

<p>我正在尝试使用Seeder和Factory创建30条新闻。但我需要创建10条具有非空字段值<code>published_at</code>(Carbon)的新闻,而其他新闻则具有随机值(Carbon/NULL)。</p> <p>在文档中,我看到了这样一个例子,它创建了5条记录,值为<code>admin (Y)</code>,以及另外5条记录,值为<code>admin (N)</code>。</p> <pre class="brush:php;toolbar:false;">User::factory() ->count(10) ->state(new Sequence( ['admin' => 'Y'], ['admin' => 'N'], )) ->create();</pre> <p>到目前为止,我使用了这段代码,但我无法弄清楚如何添加具有特定参数值<code>published_at</code>的记录数量。例如,10条使用Carbon,20条使用NULL。</p> <pre class="brush:php;toolbar:false;">/**文章播种者*/ Article::factory() ->count(30) ->state(new Sequence([ 'published_at' => Factory::create()->dateTimeBetween( now()->startOfMonth(), now()->endOfMonth() ), ])) ->create();</pre></p>
P粉043566314P粉043566314384 天前466

全部回复(1)我来回复

  • P粉957723124

    P粉9577231242023-09-05 00:50:01

    在序列闭包中,您可以访问$index属性,该属性包含迄今为止通过序列进行的迭代次数。

    以下是您可以使用的最简单的逻辑来实现您想要的结果。

    Article::factory()
    ->count(30)
    ->sequence(fn ($sequence) => [
        'published_at' => $sequence->index < 10
                          ?  Factory::create()->dateTimeBetween(
                                 now()->startOfMonth(),
                                 now()->endOfMonth()
                             );
                          : null
    ])
    ->create();

    回复
    0
  • 取消回复