简体   繁体   English

由于sortBy的Laravel分页错误

[英]Laravel pagination error because of sortBy

I am trying to paginate an eloquent object but i can't get it to work. 我正在尝试对一个雄辩的对象进行分页,但是我无法使其正常工作。 The paginate throws a error because $products is not a query builder object but a collection. 由于$ products不是查询生成器对象而是集合,因此分页器将引发错误。

// i get this value from a $POST variable
$customOrderIds = [3,2,1,4,6,5,9,8,10,7,11,12,13,14,15,16,17,20,18,19,21,22]; // I want the products ordered in this sequence
$products = Product::get()->sortBy(function($product) use($customOrderIds) 
{
    return array_search($product->id, $customOrderIds);
});

$products->paginate(5); // Error is thrown here

I want to keep the order of products that is defined in the $customOrderIds 我想保留$ customOrderIds中定义的产品顺序

In other questions they suggest to replace get() function with the paginate function but then my custom order will be only applied to the 5 items in the pagination. 在其他问题中,他们建议将get()函数替换为分页函数,但是我的自定义订单将仅应用于分页中的5个项目。

I would rather not use anything with raw sql 我宁愿不使用任何原始sql

paginate is an Eloquent method, so it won't work on your collection. paginate是一种雄辩的方法,因此不适用于您的收藏集。 However, collections have a forPage method, which you can use: 但是,集合具有forPage方法,您可以使用:

The forPage method returns a new collection containing the items that would be present on a given page number. forPage方法返回一个新集合,该集合包含将在给定页码上显示的项目。 The method accepts the page number as its first argument and the number of items to show per page as its second argument 该方法接受页码作为其第一个参数,接受每页显示的项目数作为其第二个参数

So what you'll need is 所以您需要的是

$products->forPage(1, 5);

You have to indeed replace the get with the paginate , but you'll have to do the sorting before you paginate . 您确实必须用paginate代替get ,但必须在paginate之前进行排序。 You can try something along the lines of: 您可以尝试以下方法:

Product::orderByRaw(
    'FIELD(id,3,2,1,4,6,5,9,8,10,7,11,12,13,14,15,16,17,20,18,19,21,22)'
)->paginate(5);

Sources: 资料来源:

https://laravel.com/docs/5.8/queries#raw-expressions https://laracasts.com/discuss/channels/eloquent/custom-orderby-in-laravel-query-builder https://laravel.com/docs/5.8/queries#raw-expressions https://laracasts.com/discuss/channels/eloquent/custom-orderby-in-laravel-query-builder

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

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