【问题标题】:Laravel 8 How to seed using Factories with UUID primary key?Laravel 8 如何使用带有 UUID 主键的工厂播种?
【发布时间】:2021-10-31 10:09:05
【问题描述】:

我有一个 Edtions 和 Issues 表,具有一对多关系(issues N-1 editions)。

当我尝试在问题工厂上调用 create() 方法时,我得到一个 NOT NULL 违规:

SQLSTATE[23502]:非空违规:7 错误:“id”列中的空值违反非空约束
详细信息:失败行包含 (null, 1, 12011981, null, 2021-09-01 23:09:17, 2021-09-01 23:09:17, null)。 (SQL:插入“issues”(“id”、“issuing_date”、“edition_id”、“updated_at”、“created_at”)值(?、12011981、1、
2021-09-01 23:09:17, 2021-09-01 23:09:17))。

但是我指定了我的问题工厂的 ID:

class IssueFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Issue::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $timestamp = mt_rand(1, time());
        $randomDate = date("dmY", $timestamp);

        return [
            'id' => Str::uuid(),
            'issuing_date' => $randomDate,
            'edition_id' => 1,
        ];
    }
}

我的播种机:

public function run()
{
    Edition::each(function ($edition) {
       Issue::factory()
          ->count(10)
          ->for($edition)
          ->create();
    });
}

问题表迁移:

Schema::create('issues', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->integer('edition_id');
    $table->string('issuing_date');

    $table->timestamps();
    $table->softDeletes();

    $table->foreign('edition_id')->references('id')->on('editions');
});

问题模型的相关部分:

    public $incrementing = false;

    protected $table = 'issues';
    protected $keyType = "string";
    protected $primaryKey = "id";
    protected $guarded = [];
    protected $fillable = [
        "id",
        "edition_id",
        "issuing_date"
    ];

我在这里做错了什么?

【问题讨论】:

    标签: laravel factory


    【解决方案1】:

    你必须在你的Schema中使用像下面这样的

    $table->uuid('id', 36)->primary();
    

    在你的模型中使用

    use Illuminate\Support\Str;
    
    public $incrementing = false;
    
    protected $keyType = 'string';
    
    public static function boot(){
        parent::boot();
    
        static::creating(function ($issue) {
            $issue->id = Str::uuid(36);
        });
    }
    

    下面这行也添加到你的工厂中

    use Illuminate\Support\Str;
    

    Reference Link

    【讨论】:

      猜你喜欢
      • 2015-09-16
      • 2021-01-26
      • 2017-08-02
      • 2021-04-25
      • 2020-03-18
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      相关资源
      最近更新 更多