多对多的关系有效。最初的工作迁移:
Schema::table('tag_topic', function (Blueprint $table) {
$table->integer('topic_id')->unsigned()->index();
$table->integer('tag_id')->unsigned()->index();
});
我希望删除引用项时删除数据透视表项。新迁移:
Schema::table('tag_topic', function (Blueprint $table) {
$table->foreign('topic_id')->references('id')->on('topics') ->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
});
数据透视表行项目未级联删除。
更新
我删除了表并重写了迁移,但仍然没有级联删除数据行:
Schema::create('tag_topic', function (Blueprint $table) {
$table->integer('topic_id')->unsigned();
$table->integer('tag_id')->unsigned();
$table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
});
此代码删除数据透视表行:
$tag = Tag::where('id', $tag->id)->get()->first();
$Tag->topics()->detach();
答案 0 :(得分:0)
在应用外键约束之前尝试删除旧索引。
Schema::table('tag_topic', function (Blueprint $table) {
$table->dropIndex(['topic_id']);
$table->dropIndex(['tag_id']);
$table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
});