您好,我正在尝试使用api将多个记录插入表中。但是我收到诸如“连接数据库错误”之类的错误。我该怎么解决。
下面是我的代码
public function addToCart(){
$input = Input::all();
$data['status'] = 0;
$data['error'] = true;
if(isset($input['user_id']) && array_filter($input['cart']) > 0 ){
foreach($input['cart'] as $key => $val){
if(!empty($val['quantity']) && !empty($val['price']) && !empty($val['sku']) && !empty($val['qrcode']) && !empty($val['product_id']))
{
$totalPrice = $val['quantity']* $val['price'];
$cartId = DB::table('jocom_cart')->insertGetId(array(
'user_id' => $input['user_id'],
'product_id' => $val->product_id,
'sku' => $val->sku,
'quantity' => $val->quantity,
'price' => $val->price,
'total_price' => $totalPrice,
'qrcode' => $val->qrcode
)
);
}
else{
$data['message'] = 'All field are required.';
}
return Response::json($data);
}
答案 0 :(得分:2)
创建一个数据数组,然后将该数组传递给insert function
尝试避免循环查询
$insertRecord = [];
foreach($input['cart'] as $key => $val){
if(!empty($val['quantity']) && !empty($val['price']) && !empty($val['sku']) && !empty($val['qrcode']) && !empty($val['product_id']))
{
$totalPrice = $val['quantity']* $val['price'];
$insertRecord[$key] = ['user_id'=>$input['user_id'],'product_id' => $val->product_id,... ,... ,...]; All your column with value
}
}
if(!empty($insertRecord)){
Model::insert($insertRecord); // Eloquent approach
DB::table('table')->insert($insertRecord); // Query Builder approach
}
答案 1 :(得分:0)
您的记录应该在数组中。 表格::: insert(Array)