duanji4870 2019-03-13 09:12
浏览 221
已采纳

Laravel:外键错误形成

So I am busy with making this migration and afther a ton of research, he still gives me the following error message:

SQLSTATE[HY000]: General error: 1005 Can't create table dev.bindings (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table bindings add constraint bindings_users_id_foreign foreign key (users_id) references users (id) on delete cascade on update cascade)

Code:

Schema::create('bindings', function (Blueprint $table) {
    $table->unsignedInteger('users_id');

    $table->foreign('users_id')
        ->references('id')->on('users')
        ->onDelete('cascade')
        ->onUpdate('cascade');
});

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
});

Versions:

PHP: v7.3
Laravel: v5.8.4
MariaDB: v10.3.13
Homestead: v8.1.0

As that I am aware, this should form a foreign key correctly. Any help would be appriciated!

  • 写回答

2条回答 默认 最新

  • doubi3929 2019-03-13 09:25
    关注

    Update: as other answers stated, i did not notice it, you will need to create the users table, before the foreign key can be created.

    When you do foreign keys, both fields will need to have the same properties. So in your case if you use bigIncrements your users_id needs to be an unsigned big int.

    // User table needs to be created first
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
    });
    
    Schema::create('bindings', function (Blueprint $table) {
        $table->bigInteger('users_id')->unsigned();
    
        ...
    });
    

    Also the standard is to name it user_id, this will make it easier to do relations in Laravel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘