Laravel 5: synching an extra field via pivot

后端 未结 1 559
北海茫月
北海茫月 2020-12-10 00:18

User model:

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

}


        
相关标签:
1条回答
  • 2020-12-10 00:34

    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);
    
    0 讨论(0)
提交回复
热议问题