我有以下迁移:
public function up()
{
Schema::create('topics_to_subscriptions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('topic_id')->unsigned();
$table->integer('subscription_id')->unsigned();
$table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
$table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
});
}
我的不足之处是,在使用onDelete('cascade')
时,如果我删除订阅,则所有关联的TopicsToSubscriptions
都将被删除。
当我运行App\Subscription::truncate();
时,所有订阅都会从subscriptions
表中正确删除,但不会从topics_to_subscriptions
中删除任何数据。我做错了什么?
答案 0 :(得分:1)
您不应该截断外键引用的表。我怀疑你的外键从未正确应用过。
https://laravel.com/docs/5.4/migrations#foreign-key-constraints
public function up()
{
Schema::create('youtube_topics_to_subscriptions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('topic_id')->unsigned();
$table->integer('youtube_subscription_id')->unsigned();
$table->foreign('topic_id')->references('id')->on('youtube_topics')->onDelete('cascade');
$table->foreign('youtube_subscription_id')->references('id')->on('youtube_subscriptions')->onDelete('cascade');
});
}