Eloquent 排序依据取决于字段

Eloquent Sort By depend on the field

我有这样的查询:

Product::withMin('promotions as promotion_price', 'promotion_products.price')
        ->get();

我想对结果进行排序,但我遇到了问题。如果 withMin 的结果为空,我想按另一个字段对其进行排序(假设 'product.sale_price')。或者我如何创建一个新字段,假设 'final_price',如果 promotion_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
  }
}

你试过制作 map() 吗?

Product::all()->map(function(Product $product){
   $product->final_price = null; //you can use this concept
})->get();

O(n) complexity

使用orderByRaw

 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();