gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:35:57 25 4
gpt4 key购买 nike

我通过下面的代码在 Laravel 模型中创建了一个追加属性。

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

我设置了返回值。

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

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

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

有人对此有什么建议吗?

最佳答案

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

试试这个

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

关于laravel - 如何在 Laravel 中使用附加属性进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com