问题
Here is my code:
public function updateGroupIntoDatabase(){
$group_id = 6;
$group = Group::find($group_id);
$group -> name = Input::get('groups');
$projectsIds = Input::get('projects');
$userIds = array_merge(Input::get('clients'),Input::get('workers'));
array_push($userIds, Auth::id());
$adminId = Auth::id();
if($group -> save()){
foreach($userIds as $userId){
$name = User::find($userId);
$group -> projects() -> sync($projectsIds,array('admin_id' => $adminId, 'user_id' => $userId,'user_name' => $name -> name));
}
when I execute this I get like this:
id project_id group_id admin_id user_id user_name
1 4 6 0 0
But it should for each user_id
create new record... When I use attach method It works find but when I use sync it create just one record with additional pivot fields filds 0
. Any solution for this?
回答1:
When using sync with pivot data:
$group->projects()->sync( array(
1 => array( 'admin_id' => $adminId, 'user_id' => $userId ),
2 => array( 'admin_id' => $adminId, 'user_id' => $userId ),
...
));
来源:https://stackoverflow.com/questions/31292695/how-to-use-sync-with-additional-pivot-fields-laravel-5