Laravel Eloquent 多对多 [编辑]

Posted

技术标签:

【中文标题】Laravel Eloquent 多对多 [编辑]【英文标题】:Laravel Eloquent Many to Many [Edit] 【发布时间】:2021-12-28 02:44:06 【问题描述】:

我有用户和任务的多对多表以及 user_task。可以为用户分配多项任务。

**User model:** 
public function tasks()  
  return $this->belongsToMany(Task::class, 'user_task', 'user_uuid', 'task_uuid'); 
 

**Task Model:** 
public function users()  
  return $this->belongsToMany(User::class, 'user_task', 'task_uuid', 'user_uuid'); 
 

**Controller:** 
public function store(Request $request)  
  $user = auth()->user(); 
  $tasks_uuid = $request->tasks; 
  $user->tasks()->sync($tasks_uuid); 
  return response()->json(['message' => 'Submit'], 200); 
 

但是在成功存储之后,我期望 user_uuid 但它存储用户的 id。

【问题讨论】:

一个任务可以属于多个用户吗?如果不是,那么 tasks 应该有一个 user_id 字段,因为它属于用户并且根本不会有数据透视表 是的,一个任务可以分配给多个用户。 belongsToMany 方法调用可以接受比 4 个更多的参数...第五个参数是 'parentKey'...如果您不在这里传递您想要的密钥,它只会使用默认情况下模型的主键,所以如果你想覆盖它并将它用于关系,你需要将第五个参数作为uuid 传递 【参考方案1】:

Laravel 约定假定主键名称是 'id',如果你没有遵循它,你应该在你的关系中传递主键名称 ...

belongsToMany关系定义:

BelongsToMany belongsToMany(string $related, string|null $table = 空,字符串|空 $foreignPivotKey =空,字符串|空 $relatedPivotKey = null, string|null $parentKey = null, string|null $relatedKey = null, string|null $relation = null)

对于您的情况,您的关系应该是:

**User model:** 
public function tasks()  
  return $this->belongsToMany(Task::class, 'user_task', 'user_uuid', 'task_uuid','user_uuid','task_uuid'); 
 

**Task Model:** 
public function users()  
  return $this->belongsToMany(User::class, 'user_task', 'task_uuid', 'user_uuid','task_uuid','user_uuid'); 
 

【讨论】:

以上是关于Laravel Eloquent 多对多 [编辑]的主要内容,如果未能解决你的问题,请参考以下文章

Laravel Eloquent 多对多,增量依赖

查询 Laravel Eloquent 多对多,其中所有 id 都相等

Laravel (8.x) 这个多对多过滤问题有更好的 Eloquent 查询吗?

Laravel Eloquent 三个模型之间的多对多关系

与多个中间表的多对多 Laravel Eloquent 关系

Laravel Eloquent 根据数据透视表字段条件获取多对多关系