[英]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();
}
在提交表單時,我有兩個數組:
$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
字段仍未更新/填充。
我做錯了什么,如何更新該字段?
你實際上很接近。 所需格式為:
[
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);
根據@lukasgeiter 的回答,這里有一個示例,可以為數據透視表合並兩個額外字段:
$extra = array_map(function($qualityId) use($request){
return ['quality_id' => $qualityId, 'product_id' => $request->product];
}, $arrayQualitiesIds);
$data = array_combine($arrayQualitiesIds, $extra);
dd($data);
輸出:
1 => array:2 [▼
"quality_id" => "1"
"product_id" => "5"
]
2 => array:2 [▼
"quality_id" => "2"
"product_id" => "5"
]
3 => array:2 [▼
"quality_id" => "3"
"product_id" => "5"
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.