How to order by using appended attribute in Laravel

拥有回忆 提交于 2019-12-22 05:37:14

问题


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?


回答1:


the orderBy takes an actual database field not an appended one

try this

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



回答2:


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




回答3:


$products = Product::all();
$products = $products->sortBy('total');


来源:https://stackoverflow.com/questions/21050476/how-to-order-by-using-appended-attribute-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!