mysql - 向表中添加外键

标签 mysql laravel

我想在 laravel 的 sql 数据库中的表中添加一个外键。但是添加后出现以下错误:

  [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`))  

我要添加这个键的表是这样的:

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();

    });
}

以及我所指的表格:

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();
    });
}

名称和类型相同。我收到错误还有什么可能?

更新 用户表中的“user_id”字段将是专门为每个用户创建的 GUID。这是我想在其他表中引用的字段。这可能吗?那么,据我所知,我是否需要将此字段设为 PK?

最佳答案

您可以为 users 表的 id 列创建外键。

代替:

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

使用:

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

关于mysql - 向表中添加外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29702431/

相关文章:

php - MySQL数据库: one media table or one table for images and one for videos?

php - 返回用户自己的 ID 的搜索查询

mysql - 如何合并具有相似时间戳的两行并同时返回

php - 由多个应用程序共享的数据库的单点数据

database - Eloquent 问题 : Undefined function: 7 ERROR: operator does not exist

laravel - 在 OctoberCMS 中创建产品时向用户发送通知?

laravel - 无法停用电子邮件验证 Laravel

php - 如何在MySQL中搜索从12月到1月的生日?

mysql - 在查询中使用运算符通过 mySQL 获取两个日期之间的差异

php - 我无法在 Laravel 中检索区域设置字符串