【发布时间】: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"
];
我在这里做错了什么?
【问题讨论】: