Laravel 5:通过枢轴同步一个额外的字段

Mhl*_*aka 3 php mysql pivot sync laravel

用户模型:

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

}
Run Code Online (Sandbox Code Playgroud)

职位模型:

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

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

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


$allCompanyIds
array:3 [
0 => 129
1 => 130
2 => 131
]
Run Code Online (Sandbox Code Playgroud)

运用

$user->positions()->sync($allPositionIds);
Run Code Online (Sandbox Code Playgroud)

将position_user表按预期与用户和相应的位置id同步.

但是我无法弄清楚如何填充额外的字段('company_id')

这是我期望的工作方式:

$user->positions()->sync([$allPositionIds => ['company_id' => $allCompanyIds]], false);
Run Code Online (Sandbox Code Playgroud)

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

$user->roles()->sync(array(1 => array('expires' => true)));
Run Code Online (Sandbox Code Playgroud)

我试过用这个答案

合并两个数组:

$syncData = array_combine($allPositionIds,$allCompanyIds);
Run Code Online (Sandbox Code Playgroud)

并得到$ syncData:

array:3 [
98 => 129
99 => 130
100 => 131
]
Run Code Online (Sandbox Code Playgroud)

相应地映射到位置id数组和公司ID数组,但如果我尝试

user->positions()->sync($syncData);
Run Code Online (Sandbox Code Playgroud)

我得到了 "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领域仍然没有被更新/填充.

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

luk*_*ter 8

你其实非常接近.所需格式为:

[
    98 => ['company_id' => 129],
    99 => ['company_id' => 130],
    100 => ['company_id' => 131]
]
Run Code Online (Sandbox Code Playgroud)

这应该生成正确的数组:

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

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

$user->positions()->sync($data);
Run Code Online (Sandbox Code Playgroud)

  • 是! 太好了,谢谢@lukasgeiter。太棒了!将其添加为书签,当我有足够的代表时,我将返回并投票! (2认同)