【问题标题】:Laravel Factory SequenceLaravel 工厂序列
【发布时间】:2021-02-03 05:05:01
【问题描述】:

我正在尝试为博客文章定义一个工厂。我想为published 字段设置一个Sequence。我尝试了几种不同的方法,但我还没有成功。这是我当前的实现。我怎样才能正确地做到这一点?

'published' => $this->sequence([now(), null])

我也试过了:

'published' => $this->sequence(now(), null)

我还尝试过不使用sequence() 助手:

'published' => $this->state(new Sequence([now(), null]))

//and

'published' => new Sequence([now(), null])

API 文档:https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Factories/Sequence.html

【问题讨论】:

  • 序列并不打算用于工厂的定义。如果你尝试一下,我很确定你最终会陷入无限循环。
  • @Rwd 这是我迄今为止的经验,但我认为必须有一种方法可以在工厂定义中实现这一点?如果没有,那肯定是可取的。

标签: laravel


【解决方案1】:

我试图错误地执行此操作。与其在Factory 中创建Sequence,不如在Seeder 中创建Sequence,如下所示:

public function run()
{
    BlogPost::factory()
        ->count(6)
        ->sequence(
            ['published' => now()],
            ['published' => null]
        )
        ->create();
}

【讨论】:

    【解决方案2】:

    利用Factoryconfigure()方法:

    public function configure()
    {
        return $this->sequence(
            [
                'published' => now()
            ], [
                'published' => null
            ]
        );
    }
    

    Docs 仅在工厂回调的上下文中提及 configure(),但您可以在此处使用任何 Factory::newInstance() 调用者:

    use App\Models\Post;
    
    public function configure()
    {
        return $this->afterMaking(function (Post $post) {
            //
        })->afterCreating(function (Post $post) {
            //
        })->sequence(
           //
        );
    }
    

    【讨论】:

    • 从您的问题来看,我认为您希望默认情况下在工厂中有一个序列(通过调用BlogPost::factory())。因此我的回答。
    猜你喜欢
    • 2020-11-24
    • 2020-11-20
    • 1970-01-01
    • 2017-05-29
    • 2020-01-22
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多