简体   繁体   中英

Laravel attach arrays of data to pivot

I am trying to attach arrays of data. I have collection of products and try to get individual items, and insert into pivot table. I don't want to put attach in loop because I want one db call

if($cart->packages)
    {
        foreach( $cart->packages as $k => $v)
        {
            $collection = Collection::find($k)->products;
            // dd($collection);
            $records_array[] = $k;
            $name[]['name'] = $v['name'];
            $quantity[]['quantity'] = $v['quantity'];
        }
        // dd($records_array);
        $order->collections()->attach($records_array,  $name, $quantity);
    }

First of all you need to import DB facade some where after namespace and before class name:

use Illuminate\Support\Facades\DB;

The in your controller added following for testing:

$cart = array(
    array('name' => 'some product 1', 'quantity' => '1'),
    array('name' => 'some product 2', 'quantity' => '2'),
    array('name' => 'some product 3', 'quantity' => '1'),
);

if ($cart)
{
    DB::table('order')->insert($cart);
}

I have tested on my local environment and it works.

You can take look at Running An Insert Statement

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