Laravel迁移:“外键约束格式不正确" (错误号150) [英] Laravel migration: "Foreign key constraint is incorrectly formed" (errno 150)

查看:81
本文介绍了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');
    });
}  

错误消息

[Illuminate \ Database \ QueryException]
SQLSTATE [HY000]:常规错误:1005无法创建表 meal.#sql-11d2_1 4(错误号:150外键约束为 格式不正确")(SQL:alter
meals在删除时添加约束饭食_类别_id_外来键(category_id)引用categories(id) 级联)

[Illuminate\Database\QueryException]
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 Your question has inspired me to the answer ,i adopted on laravel to automate the process without considering the creation time of the file itself ,According to workflow meals will be created before table (categories) because i have created schema file (meals) before categories. that was my fault.

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

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