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

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条)

报告相同问题?

悬赏问题

  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动