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

Bun*_*ert 6 laravel laravel-4

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

    protected $appends = array('total'=>'');
Run Code Online (Sandbox Code Playgroud)

我设置了返回的值.

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

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

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

有没有人对此提出一些建议?

Ayo*_*emi 11

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

试试这个

$products = Product::all();
$products = $products->sortBy(function($product){
    return $product->total;
});
Run Code Online (Sandbox Code Playgroud)

  • 它似乎工作和投票,但经过几次尝试它似乎并不真的.一旦你有了Collection,sortBy似乎对闭包没有任何影响,也没有通过append属性(它确实出现在集合中的每个对象中)对集合进行排序.看起来这可能是集合忽略附加值的问题,因为它们最终与"真实"属性不同.虽然我不需要删除我的upvote因为我需要编辑答案但除了通过php排序之外无法提供任何见解. (2认同)