简体   繁体   English

如何在laravel中排序后分页

[英]how to paginate after a sort by in laravel

I have a Food model.我有一个食物模型。 Each food has a price and a discount (in percent).每种食物都有价格和折扣(百分比)。 I have appended a cost attribute to hold a value which is calculated base on the first price and discount.我附加了一个成本属性来保存一个基于第一个价格和折扣计算的值。

Example :示例
We have a Food with a price of 10$.我们有一个价格为 10 美元的食物。 discount is 10%, so the cost is 9$.折扣是 10%,所以成本是 9 美元。

class Food extends Model
{
    protected $appends = ['cost'];

    public function getCostAttribute()
    {
        return $this->price - round( ($this->price*$this->discount) / 100 );
    }

}

I need to order my foods based on cost.我需要根据成本订购我的食物。 I cannot use orderBy because cost is not actually a column.我不能使用orderBy因为 cost 实际上不是一列。 so I have to use sortBy .所以我必须使用sortBy

$foods = Food::all();
$foods = $foods->sortBy(function($food){
    return $food->cost;
});

Now, how can I paginate $foods variable?现在,如何对$foods变量进行分页? Because I cannot execute following code to paginate因为我无法执行以下代码进行分页

$foods = $foods->paginate(12);

sort by has already take datas from db, so use pagination is not really helpful. sort by已经从 db 获取数据,所以使用分页并不是很有帮助。

So I recommend to change your code like this, this will reduce IO cost:所以我建议像这样改变你的代码,这将减少 IO 成本:

Food::select('*', 
             DB::raw('(price - round((price * discount) / 100)) AS cost')
            )->orderBy('cost')
             ->paginate(12)

You have to use join to sort your item base on the relationship model.您必须使用 join 根据关系模型对项目进行排序。 Try this尝试这个

$order = 'desc';
$users = Food::join('costs', 'foods.id', '=', 'costs.id')->orderBy('costs.id', 
$order)->select('foods.*')->paginate(10);

reference : [ https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship][1]参考:[ https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship][1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM