Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 无法添加外键约束-Laravel迁移错误_Mysql_Laravel_Laravel 5 - Fatal编程技术网

Mysql 无法添加外键约束-Laravel迁移错误

Mysql 无法添加外键约束-Laravel迁移错误,mysql,laravel,laravel-5,Mysql,Laravel,Laravel 5,我有多个迁移,但我认为与此问题相关的两个迁移是“作业”和“会话”迁移 工作迁移 Schema::create('job', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->timestamps(); }); 会话迁移: Schema::create('session', f

我有多个迁移,但我认为与此问题相关的两个迁移是“作业”和“会话”迁移

工作迁移

    Schema::create('job', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });
会话迁移:

    Schema::create('session', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('group_id');
        $table->unsignedBigInteger('job_id');
        $table->boolean('verified')->default(0);
        $table->date('date');
        $table->time('start_time');
        $table->time('end_time');
        $table->string('session_type');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('group_id')->references('id')->on('group');
        $table->foreign('job_id')->references('id')->on('job');
    });
现在,我在进行迁移时遇到的错误是:

SQLSTATE[HY000]:一般错误:1215无法添加外键约束 (SQL:alter table
session
add constraint
session\u job\u id\u foreign
外键(
job\u id
)引用
job
id

数据库:MySQL


我不明白这里有什么问题。这种方法一直对我有效,即使在当前的Laravel项目中。

您必须确保作业迁移在会话迁移之前

您必须确保作业迁移在会话迁移之前

处理
迁移和
外键关系时
(父-子),基于迁移文件的时间戳定义的序列,因此始终确保在子表
之前创建父表迁移。这一点很重要,因为如果父表不存在,则表示您在
子表中引用的列不存在,在这种情况下,它将通过此类错误进行处理


在您的情况下,更改时间戳将解决问题。

在处理
迁移和
外键关系
(父-子)时,根据迁移文件的时间戳定义的序列,因此始终确保在
子表
之前创建
父表
迁移。这一点很重要,因为如果父表不存在,则表示您在
子表中引用的列不存在,在这种情况下,它将通过此类错误进行处理


在您的情况下,更改时间戳可以解决问题。

迁移顺序正确吗?不确定您的意思。我确实先创建了会话迁移,然后创建了作业迁移。这就是问题吗?这就是问题所在。您尝试为不存在的表创建外键。尝试通过更改日期来重命名迁移文件。好的,是的,成功了。非常感谢。迁移顺序正确吗?不知道你的意思。我确实先创建了会话迁移,然后创建了作业迁移。这就是问题吗?这就是问题所在。您尝试为不存在的表创建外键。尝试通过更改日期来重命名迁移文件。好的,是的,成功了。非常感谢。是的,谢谢你。只需将时间戳增加到以后的日期即可。是的,谢谢。只需将时间戳增加到更晚的日期即可。