[英]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 我不想把attach放在循环中,因为我想要一个db调用
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: 首先,您需要在命名空间之后和类名之前的某些位置导入DB
外观:
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 您可以查看Running An Insert Statement
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.