如何在Laravel中使用附加属性进行排序 [英] How to order by using appended attribute in Laravel

查看:382
本文介绍了如何在Laravel中使用附加属性进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从下面的代码中在Laravel Model中创建了一个appends属性.

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

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

然后设置返回值.

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

然后我想使用total属性从数据库中订购记录

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

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

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

有人对此有何建议?

推荐答案

orderBy接受一个实际的数据库字段而不是一个附加字段

the orderBy takes an actual database field not an appended one

尝试

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

这篇关于如何在Laravel中使用附加属性进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆