How to order by using appended attribute in Larave

2020-07-06 05:56发布

I created an appends attribute in Laravel Model, from the code below.

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

And I set the returned value.

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

Then I want to order records from database by using total attribute

I tried to use Product::orderBy('total','desc')->get() but it didn't work.

Does anybody has some suggestions to this?

5条回答
混吃等死
2楼-- · 2020-07-06 06:14

As mentioned, the proposed solution using a sortBy() callback does not work with paging.
Here is an alternative to the accepted solution:

orderByRaw()

If the appended attributes can be calculated from the fields in your query you can instead use orderByRaw(), like so:

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

Check out a more advanced example here: laravel orderByRaw() on the query builder

查看更多
可以哭但决不认输i
3楼-- · 2020-07-06 06:18

use sortBy for ASC

$collection->sortBy('field');

use sortByDesc for DESC

$collection->sortByDesc('field');
查看更多
Animai°情兽
4楼-- · 2020-07-06 06:24

If working with attributes those are not always available instantly (e.g. for freshly created models).

As expansion on Ayobami Opeyemi's answer you should be able to use Collection's sortBy if you force the attribute to evaluate by calling its function directly:

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

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

查看更多
女痞
5楼-- · 2020-07-06 06:25

the orderBy takes an actual database field not an appended one

try this

$products = Product::all();
$products = $products->sortBy(function($product){
    return $product->total;
});
查看更多
爷的心禁止访问
6楼-- · 2020-07-06 06:26

You can use the sortBy method from collections.

$products = Product::all();
$products = $products->sortBy('total');
查看更多
登录 后发表回答