【问题标题】:Laravel migration MySQL foreign keyLaravel 迁移 MySQL 外键
【发布时间】:2019-09-23 13:38:25
【问题描述】:

我有两张桌子:

用户(ID、姓名)

事件(id、名称、日期、user_created_id、user_updated_id(等等)

如何在 Events 表的两个 id 和用户 id 之间建立关系?

user_created_id -> users.id
user_updated_id -> users.id

更新

$table->integer('user_created_id')->unsigned();
$table->integer('user_updated_id')->nullable();

$table->foreign('user_created_id')->references('id')->on('users');
$table->foreign('user_updated_id')->references('id')->on('users');

【问题讨论】:

  • 你问数据库里面做什么或者关系代码怎么写?
  • 我知道如何使用 Laravel Eloquent,但我不知道如何在数据库中使用 laravel 迁移。
  • 阅读@nakov 的回答。这就是你需要的
  • 在发帖SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint之前我已经尝试过了
  • 分享您的迁移文件以检查问题所在

标签: mysql laravel foreign-keys migration


【解决方案1】:

如果您的问题是如何为这两列创建外键,那么在这里:

$table->unsignedInteger('user_created_id');
$table->unsignedInteger('user_updated_id');

$table->foreign('user_created_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('user_updated_id')->references('id')->on('users')->onDelete('cascade');

如果users 表中的id 列是bigIncrements,则将unsignedInteger 替换为unsignedBigInteger

【讨论】:

  • 问题可能是因为你有不同的类型,所以请查看我在代码下方的评论。 users 表中的id 是什么类型的列。是increments 还是bigIncrements
  • 如果你把它和我的比较,那就完全不同了。你没有告诉它它引用了哪个表。所以请使用我上面的代码。
  • 对不起,是复制粘贴的问题,我更新知道帖子是正确的。
  • 您能告诉我users 表上的id 是如何定义的吗?是$table->increments('id');吗?
  • 谢谢大家,问题解决了。 Laravel 当它是一个无符号字段时,它的长度为 10,如果不是 11。我也将它无符号设置为 user_updated_id,现在可以工作了。 $table->integer('user_created_id')->unsigned(); $table->integer('user_updated_id')->unsigned()->nullable(); $table->foreign('user_created_id')->references('id')->on('users'); $table->foreign('user_updated_id')->references('id')->on('users');
【解决方案2】:

Event模型中,可以定义两种关系:

public function user_created(){
    return $this->belongsTo('App\User', 'user_created_id');
}

public function user_updated(){
    return $this->belongsTo('App\User', 'user_updated_id');
}

在您的User 模型中,您还可以定义反向关系:

public function created_events(){
    return $this->hasMany('App\Event', 'user_created_id');
}

public function updated_events(){
    return $this->hasMany('App\Event', 'user_updated_id');
}

使用这些关系商店,您可以调用$event->user_created 来检索链接到user_created_idApp\Userupdated 版本也是如此)。

使用App\User 实例,您可以调用$user->created_events 来获取App\Event 的集合(同样,与$user->updated_events 相同)。

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 2016-06-06
    • 2019-01-31
    • 2014-08-09
    • 2014-09-27
    • 2014-03-11
    • 2018-09-22
    • 2016-07-06
    • 2015-08-14
    相关资源
    最近更新 更多