为什么在Laravel中运行这段迁移代码时会触发errno 150错误?
错误原因
- 迁移执行顺序错误:外键约束要求被关联的表必须先于设置外键的表创建,你现有代码的创建顺序是details→categories→books,其中details关联尚未创建的books表、books关联尚未创建的categories表,关联表不存在导致外键创建失败,触发errno150错误。
- details表主键定义缺失:你定义了
details_id字段为unsignedBigInteger类型,但未设置为主键/自增属性,字段定义不完整也会触发表结构错误。
修正方案
- 调整迁移文件的执行顺序:三个迁移文件的文件名前缀时间戳需要保证categories最早、其次是books、最后是details,确保表的创建顺序为categories → books → details。
- 补全details表的主键定义。
修正后的完整迁移代码如下:
// 第一个执行:创建categories表 Schema::create('categories', function (Blueprint $table) { $table->id('category_id'); $table->string('category_name', 255); $table->timestamps(); }); // 第二个执行:创建books表 Schema::create('books', function (Blueprint $table) { $table->id('book_id'); $table->unsignedBigInteger('category_id'); $table->string('title', 255); $table->foreign('category_id')->references('category_id')->on('categories')->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); }); // 第三个执行:创建details表 Schema::create('details', function (Blueprint $table) { $table->id('details_id'); // 补全主键定义 $table->unsignedBigInteger('book_id'); $table->string('author', 255); $table->string('publisher', 255); $table->integer('year'); $table->longText('description'); $table->foreign('book_id')->references('book_id')->on('books')->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); });
内容的提问来源于stack exchange,提问作者Alexander Tim
相关产品推荐
相关产品推荐

