简体   繁体   中英

Laravel sync a 3 model pivot table

I want to sync a 3 model pivot table. This is how I can receive the data from my form.

$data = array(
position_id->   1 => ['user_id' => [5, 14]],
position_id->   2 => ['user_id' => [15]],
position_id->   3 => ['user_id' => [6]],
position_id->   4 => ['user_id' => [5]],
position_id->   6 => ['user_id' => [8, 3, 14]],
position_id->   7 => ['user_id' => [1]],
);

This is how I wish to store the data:

$order->crew()->sync($data);

This is how the database needs to look after the data is saved:

数据库的外观


The problem:

How can I do this?

sync() won't allow for duplicates. You're gonna have to use attach() but first, the $data array must be mapped to the proper format ( [position_id => ['user_id' => user_id]] )

collect($data)
    ->map(function($users, $position_id) {
        $arr = [];
        foreach ($users['user_id'] as $user_id) {
            $arr[] = [$position_id => ['user_id' => $user_id]];
        };
        return $arr;
    })
    ->flatten(1)
    ->each(function($position) use ($order) {
        $order->crew()->attach($position);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM