Laravel 5:通过数据透视同步额外的字段 [英] Laravel 5: syncing an extra field via pivot
问题描述
用户模型:
public function positions()
{
return $this->belongsToMany('App\Position')->withPivot('company_id')->withTimestamps();
}
位置模型:
public function users()
{
return $this->belongsToMany('App\User')->withPivot('company_id')->withTimestamps();
}
提交表单时,我有两个数组:
On form submission I have two arrays:
$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同步.
that syncs the position_user table as expected with the user and corresponding position ids.
但是我不知道如何填充多余的字段("company_id")
However I can't work out how to populate the extra field ('company_id')
这是我期望的工作方式:
This is kind of what I would expect to work:
$user->positions()->sync([$allPositionIds => ['company_id' => $allCompanyIds]], false);
我已经阅读了手册,但我只是没有看到如何处理这些数组作为示例手册中的内容似乎与以下情况有关:要填充的额外字段不是由多个项目组成的数组:
I have read the manual but I am just not seeing how to handle these arrays as the examples in the manual seem to relate to a situation where the extra field to be populated is not an array of multiple items:
$user->roles()->sync(array(1 => array('expires' => true)));
我尝试使用此合并两个数组:
$syncData = array_combine($allPositionIds,$allCompanyIds);
并获得$ syncData:
and get $syncData of :
array:3 [
98 => 129
99 => 130
100 => 131
]
相应映射到职位ID数组和公司ID数组,但如果我尝试
Which maps accordingly to position id array and company id array but if I try
user->positions()->sync($syncData);
我得到一个"SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败"-我相信它正在尝试将company_id添加为另一个position_user.position_id.但由于位置表中不存在该错误,因此会出错.
目前我的 company_id
字段仍然无法更新/填充.
Whatever I am trying at the moment my company_id
field is still not being updated/populated.
我做错了什么以及如何更新该字段?
What am I doing wrong and how do I update that field?
推荐答案
您实际上非常接近.所需格式为:
You are actually pretty close. The required format is:
[
98 => ['company_id' => 129],
99 => ['company_id' => 130],
100 => ['company_id' => 131]
]
这应该生成正确的数组:
This should generate the correct array:
$extra = array_map(function($companyId){
return ['company_id' => $companyId];
}, $allCompanyIds);
$data = array_combine($allPositionIds, $extra);
$user->positions()->sync($data);
这篇关于Laravel 5:通过数据透视同步额外的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!