简体   繁体   中英

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$. 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 );
    }

}

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;
});

Now, how can I paginate $foods variable? 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.

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)

You have to use join to sort your item base on the relationship model. 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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