我有project_group
数据透视表,其中包含以下字段:id, group_id, project_id, admin_id, user_id
我用它来组合小组和项目:
$group -> projects() -> attach($projects,array('admin_id' => Auth::user()->id));
是否可以为该数据透视表中的每条记录添加diffirent user_id。
例如:
第一条记录:
id
= 1,group_id
= 1 project_id
= 2 admin_id
= 1 user_id
= 1
第二条记录:
id
= 2,group_id
= 1 project_id
= 3 admin_id
= 1 user_id
= 1
第3条记录:
id
= 3,group_id
= 1 project_id
= 2 admin_id
= 1 user_id
= 2
第4条记录:
id
= 3,group_id
= 1 project_id
= 3 admin_id
= 1 user_id
= 2
基本上,如果我从项目html列表中选择2个项目,从html用户列表中选择2个用户,我需要获得上面示例中的结果......
答案 0 :(得分:1)
当然,像这样:
$projects = [
2 => ['admin_id' => 1, 'user_id' => 1],
3 => ['admin_id' => 1, 'user_id' => 2],
// and so on
];
$group->projects()->attach($projects);
如果我理解你的问题,你可以建立这样一个数组:
$projectsIds = [2,3];
$userIds = [1,2];
$projects = [];
$adminId = Auth::id();
foreach($userIds as $userId){
$projects += array_fill_keys($projectIds, [
'admin_id' => $adminId,
'user_id' => $userId
]);
}
$group->projects()->attach($projects);