如何对两列应用 sortBy。在 laravel eloquent

how to apply sortBy for two columns. in laravel eloquent

我的产品table包含这些数据

id name price discounted_price

我想使用 laravel eloquent 对 table 产品应用排序。 discounted_price 为 0,则排序适用于价格。 discounted_price 不是 0,则排序适用于 discounted_price。

您可以使用 Eloquent get() 方法简单地检索所有项目。之后,遍历集合并在每次迭代时检查 discounted_price 是否为 != 0。如果条件为真,只需将名为 final_price 的新项添加到集合中,其值为 discounted_price。否则,将 final_price 附加到 price

最后,使用sortBy()方法将集合按final_price

排序
        $products = Product::get();

        foreach($products as $product) {
            if($product->discounted_price != 0) {
                $product->final_price = $product->discounted_price;
            } else {
                $product->final_price = $product->price;
            }
        }

        return $products->sortBy(['final_price','asc']);

关于集合排序的进一步参考 - https://laravel.com/docs/9.x/collections#method-sortby

你可以这样做:

$products = Product::all();

return $products->map(function ($product) {
    $isDiscountPrice      = $product->discounted_price !== 0;
    $product->final_price = $product->{$isDiscountPrice ? 'discounted_price' : 'price'};
    return $product;
})->sortBy(['final_price','asc']);

在这种情况下,map() Laravel Collection 会是一个很好的解决方案!