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 unity3d机械臂
  • ¥20 判断两个表是否完全相同
  • ¥20 工控机出现散热器转一下停一下这种情况,是什么原因造成的
  • ¥15 双显卡,启动docker容器报错。
  • ¥15 想编写一个期货跨期套利的程序
  • ¥15 一个线程在sleep的时候set一个信号会起作用吗
  • ¥50 如何利用matlab将现有的地基雷达回波数据调制为机载雷达回波数据
  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线