如何在 Laravel 中使用附加属性进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21050476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to order by using appended attribute in Laravel
提问by Bun Suwanparsert
I created an appends attribute in Laravel Model, from the code below.
我从下面的代码在 Laravel 模型中创建了一个 appends 属性。
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
然后我想通过使用total
属性从数据库中订购记录
I tried to use Product::orderBy('total','desc')->get()
but it didn't work.
我尝试使用,Product::orderBy('total','desc')->get()
但没有用。
Does anybody has some suggestions to this?
有人对此有什么建议吗?
回答by Ayobami Opeyemi
the orderBy takes an actual database field not an appended one
orderBy 需要一个实际的数据库字段,而不是一个附加的字段
try this
尝试这个
$products = Product::all();
$products = $products->sortBy(function($product){
return $product->total;
});
回答by Philipp
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:
作为 Ayobami Opeyemi 答案的扩展,如果您通过直接调用其函数强制属性进行评估,您应该能够使用 Collection 的 sortBy:
$products = Product::all();
$products = $products->sortBy(function($product){
return $product->getTotalAttribute();
});
回答by eylay
use sortBy
for ASC
使用sortBy
了ASC
$collection->sortBy('field');
use sortByDesc
for DESC
使用sortByDesc
了DESC
$collection->sortByDesc('field');
回答by Peter Krebs
As mentioned, the proposed solution using a sortBy()
callback does not work with paging.
Here is an alternative to the accepted solution:
如前所述,建议的使用sortBy()
回调的解决方案不适用于分页。
这是已接受解决方案的替代方案:
orderByRaw()
orderByRaw()
If the appended attributes can be calculated from the fields in your query you can instead use orderByRaw()
, like so:
如果可以从查询中的字段计算附加属性,则可以改用orderByRaw()
,如下所示:
// For example, booking percentage
$query->orderByRaw('bookings_count / total_count');
Check out a more advanced example here: laravel orderByRaw() on the query builder
在此处查看更高级的示例: 查询构建器上的 laravel orderByRaw()
回答by guizo
$products = Product::all();
$products = $products->sortBy('total');