【问题标题】:Seed factory with booted function in model模型中具有引导功能的种子工厂
【发布时间】:2021-09-29 21:08:29
【问题描述】:

当我在模型中使用引导函数时,我想知道如何为数据播种。

目前我在模型中有这个:

class Event extends Model
{

    protected $fillable = ['title', ...];

    public static function booted()
    {
        static::creating(function ($event) {
            $event->user_id = auth()->id();
        });
    }
    ...
}

在工厂里,我有这个:

return [
    'title' => $this->faker->sentence(),
    'user_id' => User::all()->random()->id,
    ...
];

但是当我执行播种器时,我有一个错误:

SQLSTATE[23000]:完整性约束违规:1048 列“user_id”不能为空(SQL:插入eventstitlecontentuser_idstart_dateend_date,@ 987654329@, is_active, created_at, updated_at) 值 (Laudantium enim totam quibusdam mollitia aut et., Qui ducimus rerum quo necessitatibus in. Officia ea eveniet aut voluptas reiciendis quam quo. Sit eos velit tempore place ?, 2019-07-07 14:15:24, 2021-07-14 13:57:23, 24, 1, 2019-07-07 14:15:24, 2021-07-22 15:04:30) )

userId 是?

如果我删除模型中的 booted() 函数,它会起作用。

【问题讨论】:

  • 为什么他们会在从命令行播种时成为经过身份验证的用户?
  • 所以问题是 user_id 为空。你可以使用$this->faker->randomElement(User::pluck('id')->toArray())

标签: laravel factory


【解决方案1】:

在您的模型中,您可以默认分配 auth()->id(),或者,如果是 null,则可以分配您在 create 方法中分配的值:

public static function booted()
{
    static::creating(function ($event) {
        $event->user_id = auth()->id() ?? $event->user_id;
    });
}

【讨论】:

    【解决方案2】:

    您不需要创建事件的功能(因为它不会是播种中的授权用户),因此您可以禁用播种事件,Muting Eloquent Events

    Event::withoutEvents(function () {
        Event::factory()...;
    });
    

    【讨论】:

      猜你喜欢
      • 2016-07-03
      • 1970-01-01
      • 2016-10-17
      • 2013-11-27
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多