使用Laravel 5.3和Eloquent模型,尝试建立用户角色模型。
我有2个表用户和角色的主要模式,每个用户都有一个角色,每个角色都有许多用户(一对多关系)。

当我尝试在用户表中创建引用角色表中ID的外键时,出现此错误


  在Connection.php第647行中:
  
  SQLSTATE [HY000]:常规错误:1005无法创建表
  mydata。#sql-7e0_71(errno:150“外键约束错误
  形式”)(SQL:alter table“用户”添加约束
  “ user_role_id_foreign”外键(“ role_id”)引用角色(“ id”))
  
  在Connection.php第449行中:
  
  SQLSTATE [HY000]:常规错误:1005无法创建表
  mydata。#sql-7e0_71(errno:150“外键约束为
  格式不正确”)


注意:我正在使用artisan命令migrate,并且已经尝试了以下答案12

这是我的用户迁移的up()函数

public function up()
    {
        Schema::create('user', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->integer('role_id')->unsigned();
            $table->string('remember_token')->nullable();
            $table->timestamps();

            $table->foreign('role_id')->references('id')->on('role');
        });
    }


和角色表

public function up()
{
    Schema::create('role', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('description');
        $table->timestamps();
    });
}

最佳答案

您试图添加在roles表(->on('roles'))上具有引用的外键,但是在迁移文件中,您正在创建一个名为roleSchema::create('role', ...)的表。
 您需要匹配那些。

将角色表的名称更改为roles或对role表的引用。

09-25 17:15
查看更多