User Model:
public function positions() { return $this->belongsToMany('App\Position')->withPivot('company_id')->withTimestamps(); }
Position Model:
public function users() { return $this->belongsToMany('App\User')->withPivot('company_id')->withTimestamps(); }
When submitting the form, I have two arrays:
$allPositionIds array:3 [ 0 => 98 1 => 99 2 => 100 ] $allCompanyIds array:3 [ 0 => 129 1 => 130 2 => 131 ]
Using
$user->positions()->sync($allPositionIds);
which synchronizes the position_user table, as expected, with the user and the corresponding position identifiers.
However, I canโt figure out how to fill in the extra field ('company_id')
This is what I expect from work:
$user->positions()->sync([$allPositionIds => ['company_id' => $allCompanyIds]], false);
I read the manual , but I just donโt see how to handle these arrays, since the examples from the manual seem to relate to the situation where the additional field that needs to be filled is not an array of several elements:
$user->roles()->sync(array(1 => array('expires' => true)));
I tried using this answer
combine two arrays:
$syncData = array_combine($allPositionIds,$allCompanyIds);
and get $ syncData from:
array:3 [ 98 => 129 99 => 130 100 => 131 ]
Which card corresponds to an array of position id and an array of company identifiers, but if I try
user->positions()->sync($syncData);
I get "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.
No matter what I try at the moment, my company_id field is still not updated / populated.
What am I doing wrong and how to update this field?