【发布时间】:2020-12-16 10:04:31
【问题描述】:
我的 Laravel 应用程序在迁移中成功创建了所有表,但是当我删除主记录时,它无法在表中创建外键关系,甚至无法强制级联。 这是迁移。
Schema::create('articles', function (Blueprint $table) {
$table->id('id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
当我运行 php artisan migrate 时,它正在成功迁移。
λ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.11 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.1 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.07 seconds)
Migrating: 2020_08_26_122846_create_articles_table
Migrated: 2020_08_26_122846_create_articles_table (0.14 seconds)
但是,当我检查数据库时,并没有创建关系,只是为外键创建索引。 Check the Articles Table image in this link. I have marked the necessary parts
Check the Users Table image here. I have highlighted the primary key.
我已经添加了一些与用户和文章相关的工厂数据,当我删除用户时,文章将被保留为孤儿。
可能出了什么问题?
- PHP 版本:7.3.21
- MySql 版本:5.7.31
- MariaDB 版本:10.4.13
- Laravel 框架版本:7.25.0
提前谢谢你。
【问题讨论】:
-
您的表是否使用 InnoDB 引擎?
-
哇!不,那个功能是空的并且已经添加了它然后它就像魔术一样工作。谢谢!
-
@ShakilAhmmed,您介意将其添加为答案以便我标记它吗?以便将来可以帮助其他人?
-
当然,我已经将它添加为答案。
-
@ShakilAhmmed 不,你还没有,我还是会添加它..
标签: php laravel laravel-migrations laravel-relations