How to connect a different value for an additional field in a Laravel 5 pivot table

I have a project_group pivot table with these fields: id, group_id, project_id, admin_id, user_id

This I use to combine groups and projects together:

 $group -> projects() -> attach($projects,array('admin_id' => Auth::user()->id)); 

Is it possible to add diffirent user_id for each record in this pivot table.

For instance:

First recording:

id = 1, group_id = 1 project_id = 2 admin_id = 1 user_id = 1

Second entry:

id = 2, group_id = 1 project_id = 3 admin_id = 1 user_id = 1

3rd record:

id = 3, group_id = 1 project_id = 2 admin_id = 1 user_id = 2

4th record:

id = 3, group_id = 1 project_id = 3 admin_id = 1 user_id = 2

Basically, if I select 2 projects from the list of html projects and 2 users from the list of html users, I need to get the result, as in the example above ...

+6
source share
2 answers

Here is one solution, if anyone has a better way, please put here ...

 $projectsIds = [11,33]; $userIds = [1,2,4]; $adminId = Auth::id(); if($group -> save()){ foreach($userIds as $userId){ $group -> projects() -> attach($projectsIds,array('admin_id' => $adminId, 'user_id' => $userId)); } 
0
source

Of course, like this:

 $projects = [ 2 => ['admin_id' => 1, 'user_id' => 1], 3 => ['admin_id' => 1, 'user_id' => 2], // and so on ]; $group->projects()->attach($projects); 

And if I understand your problem correctly, you can build such an array as follows:

 $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); 
+1
source

Source: https://habr.com/ru/post/985622/


All Articles