问题
I Want to get products and sort it by mutator attribute in my case it's called price
i search for how to sort it and found that i can use sortBy from the collection
like that
private function search()
{
return Product::with(['firstImage', 'category'])
->sortBy('price');
}
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');
}
So how can i add paginate in this case?
Edit
price mutator
public function getPriceAttribute()
{
return $this->sell_price - (($this->discount * $this->sell_price) / 100);
}
回答1:
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);
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 Docs: https://laravel.com/docs/master/queries#ordering-grouping-limit-and-offset
回答2:
You must use paginate(9) after sortBy() function.
So you must edit second code like this :
private function search()
{
return Product::with(['firstImage', 'category'])
->sortBy('price')->paginate(9);
}
来源:https://stackoverflow.com/questions/59708229/cant-use-paginate-when-use-sortby-in-laravel