php - 无法使用 Mysql 在 Laravel 中创建外键

标签 php mysql laravel laravel-5 eloquent

我有一个项目,我首先在命令提示符下调用了这两个命令:

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/

相关文章:

php - 重定向后获取主机的IP地址和HTTP状态

php - 如何从联结表中检索值作为字符串?

MySQL 4.0 乱码无法转换为较新的 MySQL

php - Laravel Restfull Controller 和路由 ajax/sync 请求

javascript - 在 vuejs 中完成 @sumit.prevent 之后,有什么方法可以调用 onsumit 事件吗?

php - 安排博客文章(不是 Blogger,不是 WordPress)

php - PHP 中的简历/CV 解析

javascript - 从不同的表中选择并组织相同的列

javascript - 使用php将浏览器地理位置插入到mysql表中?

laravel 7 使用 uuid 外键