为了账号安全,请及时绑定邮箱和手机立即绑定

errno: 150 “外键约束的格式不正确”但检查我知道的一切

errno: 150 “外键约束的格式不正确”但检查我知道的一切

PHP
慕娘9325324 2021-06-16 14:17:12
问题运行迁移时,最后一个表以标题中的错误结束。我的数据库是本地 MySQL。错误Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table shopping_list_develop。#sql-1698_2b(errno: 150 "外键约束形成不正确") (SQL: alter table productsadd constraintproducts_shopping_list_id_foreign外键 ( shopping_list_id) 引用shopping_lists( id) on delete set null on update cascade)已经试过了这是我检查的内容:父表 ( shopping_lists) 在子表 ( products)之前创建。外键shopping_list_id与它引用的列的类型相同。这两个表,shopping_lists并products具有相同的数据库引擎(InnoDB)。我已阅读其他答案,但找不到解决方案。迁移2019_05_13_192170_create_shopping_lists_table.php<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Carbon\Carbon;class CreateShoppingListsTable extends Migration {    public function up()    {        Schema::create('shopping_lists', function(Blueprint $table) {            $table->bigIncrements('id');            $table->string('name')->nullable()->default(Carbon::now()->toDateString());            $table->unsignedBigInteger('user_id');            $table->timestamps();            $table->foreign('user_id')->references('id')->on('users')                        ->onDelete('cascade')                        ->onUpdate('cascade');        });    }    public function down()    {        Schema::table('shopping_lists', function(Blueprint $table) {            $table->dropForeign(['user_id']);        });        Schema::dropIfExist('shopping_lists');    }}
查看完整描述

1 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

在您的2019_05_13_192700_create_products_table.php迁移中, onDelete 您将值设置为 null。

$table->foreign('shopping_list_id')->references('id')->on('shopping_lists')
                        ->onDelete('set null')
                        ->onUpdate('cascade');

但是您声明的列不可为空

$table->unsignedBigInteger('shopping_list_id');

尝试通过执行以下操作使该列可以为空:

$table->unsignedBigInteger('shopping_list_id')->nullable();


查看完整回答
反对 回复 2021-06-19
  • 1 回答
  • 0 关注
  • 150 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号