如何将sync()与其他枢轴字段一起使用[Laravel 5]

时间:2015-07-08 12:28:50

标签: php laravel-5 sync pivot-table

这是我的代码:

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

    }

当我执行此操作时,我会这样:

id  project_id  group_id admin_id user_id  user_name
1   4           6        0        0

但是应该为每个user_id创建新记录...当我使用attach方法时它可以找到但是当我使用sync时,它只创建一个带有附加数据透视字段filds 0的记录。对此有何解决方案?

1 个答案:

答案 0 :(得分:1)

与枢轴数据同步使用时:

$group->projects()->sync( array( 
    1 => array( 'admin_id' => $adminId, 'user_id' => $userId ),
    2 => array( 'admin_id' => $adminId, 'user_id' => $userId ),
    ...
));