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.

Code

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');
    });
}  

Error message

[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’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相关问答推荐

如何在 Laravel 中获取特定月份的最后一个日期?

如何在Laravel中创建自定义单项集合

vagrant会损坏你的电脑. | macOS v12(蒙特雷)#13132

LARAVEL 从多个表中获取重复的行

为什么删除查询执行 Laravel

我的共享主机上的每个帖子请求都出现 503 服务不可用

如何在 Laravel 中使用 Vue 路由?

调用字符串上的成员函数

Laravel:在失败时处理 findOrFail()

Lumen 中的自定义 404 页面

Carbon现在时间错了

验证规则 required_if 与其他条件(Laravel 5.4)

Laravel 5.3 - 将多个文件附加到 Mailables

Laravel:如何在没有数据库的情况下对用户进行身份验证

laravel 5中的配置缓存导致找不到视图

如何从 Laravel 中的 hasMany() 关系中获取所有结果?

Laravel:验证 json 对象

Laravel Eloquent 多态一对一?

Carbon解析到 ISO8601

laravel:如何获取 eloquent 模型的列名?