我有一个项目,我首先在命令提示符下调用了这两个命令:
php artisan make:model Music -m
php artisan make:model Artist -m
然后我像这样在音乐迁移文件中创建一个外键:
public function up()
{
Schema::create('musics', function (Blueprint $table) {
$table->increments('id');
$table->integer('artist_id')->unsigned();
$table->timestamps();
$table->foreign('artist_id')->references('id')->on('artists');
});
}
现在当我运行 migrate 命令时:
php artisan migrate
但是我有一个错误:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `musics` add constraint `musics_artist_id_foreign` foreign key (`artist_id`) references `artists` (`id`) on delete cascade)
at D:\sites\laravel\MrMusic\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
D:\sites\laravel\MrMusic\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
2 PDOStatement::execute()
D:\sites\laravel\MrMusic\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
Please use the argument -v to see more details.
注意:我将测试一些方法,比如为两个字段设置索引,...
最佳答案
订购问题。您必须先创建 artists
表。 musics.artist_id
无法引用尚不存在的 key :
php artisan make:model Artist -m
php artisan make:model Music -m
关于php - 无法使用 Mysql 在 Laravel 中创建外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50438502/