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

时间:2015-05-13 17:51:42

标签: php mysql laravel pivot sync

用户模型:

$ ./bin/getlinebasic_noenter

 Type something (16 char or less):
 pressing [enter] doesn't count...

 Type something (16 char or less): 12345678901234567890

   You entered: '1234567890123456'

职位模型:

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
]

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

但是,我无法确定如何填充额外字段(' company_id')

这是我期望的工作方式:

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

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

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

我尝试过使用此answer

组合两个数组:

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

并获取$ syncData:

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

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

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

我得到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.字段仍未更新/填充。

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

1 个答案:

答案 0 :(得分:7)

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

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