如何将sync()与其他枢轴字段一起使用[Laravel 5] [英] How to use sync() with additional pivot fields [Laravel 5]

查看:61
本文介绍了如何将sync()与其他枢轴字段一起使用[Laravel 5]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

但是它应该为每个user_id创建一个新记录...当我使用attach方法时,它可以工作,但是当我使用同步时,它只创建一个带有附加枢轴字段filds 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?

推荐答案

与枢轴数据一起使用同步时:

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

这篇关于如何将sync()与其他枢轴字段一起使用[Laravel 5]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆