如何在Laravel中使用附加属性进行排序

时间:2014-01-10 17:20:02

标签: laravel laravel-4

我在Laravel Model中创建了一个追加属性,来自下面的代码。

    protected $appends = array('total'=>'');

我设置了返回的值。

    public function getTotalAttribute(){
           return ProductPart::where('product_id',$this->id)->count();
    }

然后我想使用total属性

从数据库中订购记录

我尝试使用Product::orderBy('total','desc')->get(),但它没有用。

有人对此有一些建议吗?

5 个答案:

答案 0 :(得分:9)

orderBy采用实际的数据库字段而不是附加的

试试这个

$products = Product::all();
$products = $products->sortBy(function($product){
    return $product->total;
});

答案 1 :(得分:1)

如果使用属性,这些属性并不总是立即可用(例如,对于新创建的模型)。

作为对Ayobami Opeyemi答案的扩展,如果您通过直接调用属性来强制评估属性,则应该可以使用Collection的sortBy:

$products = Product::all();
$products = $products->sortBy(function($product){
    return $product->getTotalAttribute();
});

https://laravel.com/docs/master/collections#method-sortby

答案 2 :(得分:1)

sortBy用于 ASC

$collection->sortBy('field');

sortByDesc用于 DESC

$collection->sortByDesc('field');

答案 3 :(得分:0)

如前所述,使用sortBy()回调的建议解决方案不适用于分页。
这是公认的解决方案的替代方法:

orderByRaw()

如果可以从查询的字段中计算出附加属性,则可以改用orderByRaw(),如下所示:

// For example, booking percentage
$query->orderByRaw('bookings_count / total_count');

在此处查看更高级的示例: laravel orderByRaw() on the query builder

答案 4 :(得分:-1)

$products = Product::all();
$products = $products->sortBy('total');
相关问题