Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

php - Laravel 5: syncing an extra field via pivot

User model:

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

}

Positions model:

public function users()
{
 return $this->belongsToMany('AppUser')->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
]

Using

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

that syncs the position_user table as expected with the user and corresponding position ids.

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

I have tried using this answer

to combine the two arrays:

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

and get $syncData of :

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

Which maps accordingly to position id array and company id array but if I try

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

I get a "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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...