如何将对象与 Laravel 中的许多项目同步
How do I sync an object with many items in Laravel
我在 Laravel 中有这个:
form: {
id: null,
sale_number: 2,
client: null,
products: [
{ product_id:"",description: "", quantity: null, price: null }
],
},`
如果form{}
是模型中的请求,如何同步多个产品?
我有 pivot table product_sale
以及额外的字段数量和价格。
我试过了...
$items = $request->products;
$new= [];
foreach( $items as $key => $item){
$new[$item['product_id']]= array('quantity' => 0,'price'=>0);
}
$sale->products()->sync($new);
作为示例,但无法让每个产品的 product_id
同步。
The error says: "Illegal string offset 'product_id'"
非常感谢。
1) create your sale
2) create your products
3) sync them
像这样:
/** @var array $data */
$data = $request->all();
// extract products from the input array
$products = array_get($data, 'products');
unset($data['products']);
$saleModel = \DB::transaction(function() use ($data, $products) {
$sale = SaleModel::create($data);
$productModels = [];
foreach($products as $product) {
$productModel = ProductModel::create($product);
$productModels[$productModel->id] = $productModel;
}
$productIds = array_keys($productModels);
$sale->products()->sync($productIds);
return $sale->fresh();
});
我在 Laravel 中有这个:
form: {
id: null,
sale_number: 2,
client: null,
products: [
{ product_id:"",description: "", quantity: null, price: null }
],
},`
如果form{}
是模型中的请求,如何同步多个产品?
我有 pivot table product_sale
以及额外的字段数量和价格。
我试过了...
$items = $request->products;
$new= [];
foreach( $items as $key => $item){
$new[$item['product_id']]= array('quantity' => 0,'price'=>0);
}
$sale->products()->sync($new);
作为示例,但无法让每个产品的 product_id
同步。
The error says: "Illegal string offset 'product_id'"
非常感谢。
1) create your sale
2) create your products
3) sync them
像这样:
/** @var array $data */
$data = $request->all();
// extract products from the input array
$products = array_get($data, 'products');
unset($data['products']);
$saleModel = \DB::transaction(function() use ($data, $products) {
$sale = SaleModel::create($data);
$productModels = [];
foreach($products as $product) {
$productModel = ProductModel::create($product);
$productModels[$productModel->id] = $productModel;
}
$productIds = array_keys($productModels);
$sale->products()->sync($productIds);
return $sale->fresh();
});