我发送了Axios的多个产品对象数组。这是我的confirmPurchases()
方法,通过这种方法我将一个数组发送到laravel控制器。
confirmPurchases()
{
axios
.post(`/sells/sellProduct/`, this.bags)
.then( res => {
console.log(res.data);
} );
}
我的发送阵列看起来像这样
[
{ product_id: 1 , product_name: "product 1" , quantity: 1 },
{ product_id: 2 , product_name: "product 3" , quantity: 1 },
{ product_id: 3 , product_name: "product 2" , quantity: 1 }
]
当我打算用foreach
的Eloquent Model创建多个时间时,我得到了可怕的错误
public function sellProduct(Request $request)
{
foreach( $request as $product ){
Sell::create([
'product_id' => $product->product_id,
'sell_price' => $product->sell_price,
'quantity' => $product->quantity
]);
}
}
你能建议我这样做的好方法吗?
qazxsw poi变量不是一个实际的数组,所以你不能通过php中的qazxsw poi迭代这个。
因为,起初$request
需要制作阵列,然后按照您的意愿开展业务:)
foreach
您正在使用请求对象而不是实际数组。您可以做什么:假设您的发送阵列与卖方属性匹配。
$request
public function sellProduct(Request $request)
{
$products = json_decode($request->getContent() , true);
foreach( $products as $product )
{
Sell::create([
'product_id' => $product['product_id'],
'sell_price' => $product['sell_price'],
'quantity' => $product['quantity']
]);
}
}
用于一次插入多个雄辩数据