简体   繁体   English

将外键添加到表

[英]Add Foreign Key to table

I want to add a foreign key to a table in my sql database in laravel. 我想在laravel中的sql数据库中的表中添加一个外键。 But after adding I get the following error: 但添加后我得到以下错误:

  [Illuminate\Database\QueryException]                                                                                                                                                                   
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `userroles` add constraint userroles_user_id_foreign foreign key (`user_id`) references `users` (`user_id`))  

The table where I am adding this key to is this: 我要添加此密钥的表是:

public function up()
{
    Schema::create('userroles', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('user_id');
        $table->foreign('user_id')->references('user_id')->on('users');
        $table->string('role_id');
        $table->timestamps();

    });
}

And the table where I am referring to: 和我所指的表格:

public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('user_id');
        $table->string('name');
        $table->smallInteger('is_responder')->default(0);
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
}

The name and the type are the same. 名称和类型是相同的。 What else could it be that I get the error? 还有什么可以得到错误?

Update The field "user_id" in the users table will be a GUID specifically created to each user. 更新 users表中的字段“user_id”将是专门为每个用户创建的GUID。 This is the field I would like to reference to within other tables. 这是我想在其他表中引用的字段。 Is this possible? 这可能吗? So do I need to make this field a PK then, as far as I understand? 那么,据我所知,我需要将此字段设为PK吗?

You can create foreign key to id column of users table. 您可以为users表的id列创建外键。

Instead of: 代替:

$table->string('user_id');
$table->foreign('user_id')->references('user_id')->on('users');

Use: 采用:

$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM