本文介绍了在laravel中排序后如何分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个食物模型.每种食物都有价格和折扣(以百分比为单位).我附加了一个cost属性,以保存基于第一个价格和折扣计算得出的值.

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.

示例:
我们有一种价格为10 $的食物.折扣是10%,因此费用是9 $.

Example:
We have a Food with a price of 10$. discount is 10%, so the cost is 9$.

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

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

}

我需要根据费用订购食物.我不能使用 orderBy ,因为cost实际上不是一列.所以我必须使用 sortBy .

I need to order my foods based on cost. I cannot use orderBy because cost is not actually a column. so I have to use sortBy.

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

现在,如何对 $ foods 变量进行分页?因为我无法执行以下代码进行分页

Now, how can I paginate $foods variable? Because I cannot execute following code to paginate

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

推荐答案

排序依据已经从db获取数据,因此使用分页并没有真正的帮助.

sort by has already take datas from db, so use pagination is not really helpful.

因此,我建议像这样更改您的代码,这样可以减少IO成本:

So I recommend to change your code like this, this will reduce IO cost:

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

这篇关于在laravel中排序后如何分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:49