【发布时间】:2020-08-01 19:23:20
【问题描述】:
我编写了迁移并且它们运行良好,直到我尝试制作它们 on delete cascade
我添加了$table->engine = 'InnoDB',没关系。
但是在播种机中,当我尝试运行它们时出现错误
PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`mohajerat`.`comments`, CONSTRAINT `comments_comment_id_foreign` FOREIGN KEY (`comment_id`) REFERENCES `comments` (`id`) ON
DELETE CASCADE)")
我知道 stackoverflow 中有一些问题,但没有一个对我有帮助。所以我在这里问任何人都可以提供帮助 这是我的迁移:
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->engine = 'InnoDB';
$table->morphs('commentable');
$table->string('body', 250);
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->foreignId('comment_id')->constrained('comments')->onDelete('cascade');
$table->timestamps();
});
这是我的播种机:
Schema::disableForeignKeyConstraints();
Comment::truncate();
Schema::enableForeignKeyConstraints();
$users = \App\Models\User::all()->toArray();
foreach ($users as $key => $user) {
// $comment = \App\Models\Comment::all()->random();
$post = \App\Models\Article::all()->random();
// dd($user, $post);
factory(Comment::class)->create([
'user_id' => $user['id'],
'commentable_id' => $post->id,
'commentable_type' => get_class($post),
'comment_id' => 0
]);
}
如果你知道,请告诉我。 谢谢!
【问题讨论】:
-
外键引用的列声明在哪里?您已创建外键但尚未将其分配给任何列
标签: mysql sql laravel migration