我有这样的疑问:
Product::withMin('promotions as promotion_price', 'promotion_products.price')
->get();我想对结果进行排序,但我有问题。如果withMin的结果为null,我想按另一个字段对其进行排序(让我们说'product.sale_price')。或者,如果promotion_price为null,那么如何创建一个新的字段,比如‘sale_price’,使用sale_price。
我已经尝试过的是:
在get()之后添加以下内容
->sortByDesc(function ($product){
if($product->promotion_price === null)
{
return $product->sale_price;
}
else
{
return $product->promotion_price;
}
}结果仍未排序
{
"0": {
"id": 2,
"title": "Test Product",
"sale_price": 990000,
"promotion_price": 50000
},
"1": {
"id": 3,
"title": "Test Paimon s",
"sale_price": 99999,
"promotion_price": 50000
},
"2": {
"id": 4,
"title": "Asus Nvidia RTX 3090",
"sale_price": 56500000,
"promotion_price": 50000
},
"3": {
"id": 5,
"title": "Asus Nvidia RTX 3080",
"sale_price": 42500000,
"promotion_price": 10000
},
"4": {
"id": 6,
"title": "Gigabyte Nvidia RTX 3090",
"sale_price": 53500000,
"promotion_price": null
},
"5": {
"id": 7,
"title": "Gigabyte Nvidia RTX 3080",
"sale_price": 40000000,
"promotion_price": null
},
"6": {
"id": 8,
"title": "Zotac Nvidia RTX 3090",
"sale_price": 49500000,
"promotion_price": null
}
}发布于 2022-04-18 08:46:36
Product::withMin('promotions as promotion_price', 'promotion_products.price')
->orderByRaw("CASE WHEN promotion_price is null then sale_price else promotion_price end DESC" )
->get();发布于 2022-04-18 06:48:41
你试着做地图了吗?
Product::all()->map(function(Product $product){
$product->final_price = null; //you can use this concept
})->get();O(n)复杂性
https://stackoverflow.com/questions/71908264
复制相似问题