雄辩的排序取决于领域
我有这样的查询:
Product::withMin('promotions as promotion_price', 'promotion_products.price')
->get();
我想对结果进行排序,但我有问题。如果withmin的结果如果为null,我想通过另一个字段对其进行排序(假设“ product.sale_price”)。或者,如果pasterion_price为null使用sale_price,我该如何制作一个新字段,可以说“ final_price”。
我已经尝试过的内容:
添加此之后()
->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
}
}
I have a query like this:
Product::withMin('promotions as promotion_price', 'promotion_products.price')
->get();
I want to sort the result but i have problem. if the result of withMin if null i want to sort it by another field (lets say 'product.sale_price'). Or how can i make a new field, lets say 'final_price', if promotion_price is null use sale_price.
What i already tried:
add this after get()
->sortByDesc(function ($product){
if($product->promotion_price === null)
{
return $product->sale_price;
}
else
{
return $product->promotion_price;
}
}
the result still not sorted
{
"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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 orderbybyraw
use orderByRaw
您是否尝试制作Map()?
Did you try to make map()?