小编典典

Laravel 5:通过数据透视同步额外的字段

mysql

用户模型:

public function positions()
{
 return $this->belongsToMany('App\Position')->withPivot('company_id')->withTimestamps();

}

职位模型:

public function users()
{
 return $this->belongsToMany('App\User')->withPivot('company_id')->withTimestamps();
}

在表单提交时,我有两个数组:

$allPositionIds
array:3 [
0 => 98
1 => 99
2 => 100
]


$allCompanyIds
array:3 [
0 => 129
1 => 130
2 => 131
]

使用

$user->positions()->sync($allPositionIds);

可以按预期将position_user表与用户和相应的位置ID同步。

但是我不知道如何填充多余的字段(“ company_id”)

这是我期望的工作方式:

$user->positions()->sync([$allPositionIds => ['company_id' => $allCompanyIds]], false);

我已经阅读了手册,但是我只是看不到如何处理这些数组,因为手册中的示例似乎与以下情况有关:要填充的额外字段不是多个项目的数组:

$user->roles()->sync(array(1 => array('expires' => true)));

我尝试使用此答案

合并两个数组:

$syncData = array_combine($allPositionIds,$allCompanyIds);

并获得$ syncData的:

array:3 [
98 => 129
99 => 130
100 => 131
]

哪个对应于位置ID数组和公司ID数组,但如果我尝试

user->positions()->sync($syncData);

我得到一个 "SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails" - I believe it is trying to add in the company_id as another position_user.position_id but then it errors out as that doesn't exist in the positions table.

无论目前我在尝试什么,我的company_id领域仍然没有更新/填充。

我做错了什么,该如何更新该字段?


阅读 318

收藏
2020-05-17

共1个答案

小编典典

您实际上非常接近。所需格式为:

[
    98 => ['company_id' => 129],
    99 => ['company_id' => 130],
    100 => ['company_id' => 131]
]

这应该生成正确的数组:

$extra = array_map(function($companyId){
    return ['company_id' => $companyId];
}, $allCompanyIds);

$data = array_combine($allPositionIds, $extra);

$user->positions()->sync($data);
2020-05-17