在Laravel中使用sortby时无法使用分页 [英] can't use paginate when use sortby in Laravel

查看:185
本文介绍了在Laravel中使用sortby时无法使用分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取产品并按mutator attribute对其进行排序,在我的情况下,它称为price

I Want to get products and sort it by mutator attribute in my case it's called price

我搜索了如何对其进行排序,发现我可以使用collection

i search for how to sort it and found that i can use sortBy from the collection

喜欢

private function search()
{   
    return Product::with(['firstImage', 'category'])
        ->sortBy('price');
}

它工作正常,但是当我尝试添加paginate时,什么也没有发生,并且响应中没有分页显示

it works fine, but when I try to add paginate nothing happens and there is no paginate in the response

private function search()
{   
    return Product::with(['firstImage', 'category'])
        ->paginate(9)->sortBy('price');

}

那么在这种情况下如何添加paginate?

So how can i add paginate in this case?

修改

price变异器

public function getPriceAttribute()
{
    return $this->sell_price - (($this->discount * $this->sell_price) / 100);
}

推荐答案

不幸的是,无法在集合上调用paginate().您可以手动对收集结果进行分页或修改查询,然后使用addSelectorderByRaw包括突变值:

Unfortunately there is no way to call paginate() on collection. You may manually paginate the collection result or modify your query and use addSelect or orderByRaw to include mutated value:

use Illuminate\Support\Facades\DB;

Product::select('*', DB::raw('(sell_price - ((discount * sell_price) / 100)) AS price'))
        ->orderBy('price')
        ->paginate(9);

顺便说一句,如果您的折扣是一个常数值,我想您可以通过sell_price列而不是price突变值来获得相同的结果,因此请尝试使用orderBy('sell_price')而不是sortBy('price'):

By the way, I think you'll get the same result to order by sell_price column instead of price mutated value if your discount is a constant value, so try orderBy('sell_price') instead of sortBy('price'):

Product::with(['firstImage', 'category'])
        ->orderBy('sell_price')
        ->paginate(9);

Laravel文档: https://laravel.com/docs/master/queries#ordering-grouping-limit-and-offset

Laravel Docs: https://laravel.com/docs/master/queries#ordering-grouping-limit-and-offset

这篇关于在Laravel中使用sortby时无法使用分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆