Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach different value for additional field in pivot table Laravel 5

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

This I use to attach group and projects together:

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

Is it possible to for every record in that pivot table add diffirent user_id.

For example:

First record:

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

Second record:

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

3th 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

Basicly if I select 2 projects from projects html list and 2 users from html users list I need to get result like in example above...

like image 654
Vladimir Djukic Avatar asked Apr 21 '15 15:04

Vladimir Djukic


1 Answers

Sure, 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 understood your problem right, you can build such an array like this:

$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);
like image 58
lukasgeiter Avatar answered Oct 06 '22 01:10

lukasgeiter