[英]Laravel collection->push() not working properly
I want to collect product and push to the session cart.我想收集产品并推送到会话购物车。
$product= Product::find(1);
$product2= Product::find(2);
session(['cart' => collect($product)]);
session(['cart' => session('cart')->push($product2)])
This is my output with some dummy data.这是我的一些虚拟数据的输出。
{
"0": {
"id": 2,
"sku": "SKU914",
"price": 1.0,
"special_price": 0.91,
"weight": 763,
"barcode": "0434120288572",
"created_at": "2020-01-31 14:39:53",
"updated_at": "2020-01-31 14:39:53"
},
"id": 1,
"sku": "SKU579",
"price": 22.8,
"special_price": 19.14,
"weight": 478459,
"barcode": "1390377688",
"created_at": "2020-01-31 14:34:59",
"updated_at": "2020-01-31 14:34:59"
}
The second product ($product2) which I pushed become outside of the array.我推送的第二个产品 ($product2) 位于数组之外。 How should I do to make it like "0": {}, "1": {}
我该怎么做才能使它像"0": {}, "1": {}
as per your request simply use like this根据您的要求,只需像这样使用
session(['cart' => collect($product)]);
$card1[] = session('cart');
$card1[] = collect($product1);
session(['cart' => $card1])
$card2[] = session('cart');
$card2[] = collect($product2);
session(['cart' => $card2])
or you can use whereIn()或者你可以使用whereIn()
$products = Product::whereIn("id",[1,2])->get()->toArray();
session(['cart' => $products])
or can use array_merge或者可以使用array_merge
session(['cart' => collect($product)]);
$cart = array_merge(session('cart'),collect($product2));
session(['cart' => $cart])
you don't need to merge anything你不需要合并任何东西
2 query will be slow so better to run only one query 2 查询会很慢,所以最好只运行一个查询
$Ids = [1,2];
if(true) { // can add any condtion here
array_push(3); // if you need to push new id
}
$product= Product::whereIn("id",$Ids)->get();
session(['cart' => $product]);
you can apply whereIn()
condition您可以应用whereIn()
条件
Just place $product in an array.只需将 $product 放在一个数组中。
session(['cart' => collect([$product])]);
session(['cart' => session('cart')->push($product2)]);
Or just push或者只是推
session(['cart' => session('cart')->push($product)]);
session(['cart' => session('cart')->push($product2)]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.