How to use sync() with additional pivot fields [Laravel 5] [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-12 06:15:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!