Laravel 迁移:“外键约束形成错误";(错误号 150) [英] Laravel migration: "Foreign key constraint is incorrectly formed" (errno 150)

查看:26
本文介绍了Laravel 迁移:“外键约束形成错误";(错误号 150)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迁移我的数据库时,出现此错误.下面是我的代码,后面是我在尝试运行迁移时遇到的错误.

When migrating my DB, this error appears. Below is my code followed by the error that I am getting when trying to run the migration.

代码

public function up()
{
    Schema::create('meals', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('category_id')->unsigned();
        $table->string('title');
        $table->string('body');
        $table->string('meal_av');
        $table->timestamps();
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
        $table->foreign('category_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
    });
}  

错误信息

[照亮数据库查询异常]
SQLSTATE[HY000]:一般错误:1005 无法创建表meal.#sql-11d2_1 4 (errno: 150 "外键约束为格式不正确") (SQL: alter
meals 添加约束级联)

[IlluminateDatabaseQueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table meal.#sql-11d2_1 4 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter
table meals add constraint meals_category_id_foreign foreign key (category_id) references categories (id) on delete cascade)

推荐答案

@JuanBonnett 的 问题启发了我找到答案.我使用 Laravel 来自动化这个过程,而不考虑文件本身的创建时间.根据工作流程,餐食"将在另一个表(类别)之前创建,因为我在类别之前创建了它的架构文件(餐食).那是我的错.

@JuanBonnett’s question has inspired me to find the answer. I used Laravel to automate the process without considering the creation time of the file itself. According to the workflow, "meals" will be created before the other table (categories) because I created its schema file (meals) before categories. That was my fault.

这篇关于Laravel 迁移:“外键约束形成错误";(错误号 150)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆