简体   繁体   English

雄辩的-按月,年和分页分组

[英]Eloquent - Group By Month, Year and Paginate

I am trying to list entries in a table by Month, Year: 我试图按月,年列出表中的条目:

  • May, 2015 2015年5月
    • Item 1 项目1
    • Item 2 项目2
    • Item 3 项目3
  • June, 2015 2015年6月
    • Item 1 项目1
    • etc.. 等等..

I have achieved this with the following code but I would also like to paginate the results . 我已经用下面的代码实现了这一点,但我也想对结果进行分页 I have tried many different things but none of them seem to work, I am using Laravel 5. 我尝试了许多不同的方法,但是似乎都没有用,我正在使用Laravel 5。

$events = App\Events->orderBy('start', 'asc')->get()->groupBy(function($date) {
            return $date->start->format('F, Y');
        });

Here is the output for the above query: 这是上述查询的输出:

{
    "April, 2015": [
        {
            "id": "10",
            "event_type_id": "1",
            "user_id": "1",
            "title": "Testing",
            "slug": "testing",
            "start": "2015-04-23 17:00:00",
            "end": "2015-04-23 17:40:00",
            "description": "<h1>MEETING!</h1><p>Let's try this in HTML!<br></p>",
            "created_at": "2015-04-19 14:18:33",
            "updated_at": "2015-04-21 22:07:41",
            "type": {
                "id": "1",
                "name": "General",
                "slug": "general",
                "created_at": "2015-04-18 11:24:00",
                "updated_at": "2015-04-18 11:24:04"
            }
        }
    ],
    "May, 2015": [
        {
            "id": "12",
            "event_type_id": "1",
            "user_id": "1",
            "title": "Test Event",
            "slug": "test-event",
            "start": "2015-05-15 18:00:00",
            "end": null,
            "description": "<p>This is a test event with just a start time</p>",
            "created_at": "2015-04-21 14:59:56",
            "updated_at": "2015-05-02 18:37:53",
            "type": {
                "id": "1",
                "name": "General",
                "slug": "general",
                "created_at": "2015-04-18 11:24:00",
                "updated_at": "2015-04-18 11:24:04"
            }
        },
        {
            "id": "9",
            "event_type_id": "1",
            "user_id": "1",
            "title": "Monthly Meeting",
            "slug": "monthly-meeting",
            "start": "2015-05-23 14:00:00",
            "end": "2015-04-16 20:00:00",
            "description": "<p>It's a long monthly meeting!</p>",
            "created_at": "2015-04-19 13:13:45",
            "updated_at": "2015-05-03 08:45:56",
            "type": {
                "id": "1",
                "name": "General",
                "slug": "general",
                "created_at": "2015-04-18 11:24:00",
                "updated_at": "2015-04-18 11:24:04"
            }
        }
    ],
    "June, 2015": [
        {
            "id": "11",
            "event_type_id": "1",
            "user_id": "1",
            "title": "Another Meeting Saved",
            "slug": "another-meeting-saved",
            "start": "2015-06-19 18:00:00",
            "end": null,
            "description": "<p>It's another meeting afterall</p>",
            "created_at": "2015-04-20 15:03:30",
            "updated_at": "2015-05-03 08:46:19",
            "type": {
                "id": "1",
                "name": "General",
                "slug": "general",
                "created_at": "2015-04-18 11:24:00",
                "updated_at": "2015-04-18 11:24:04"
            }
        }
    ]
}

With LengthAwarePaginator - 使用LengthAwarePaginator-

$paginator = new LengthAwarePaginator($events, count($events), 1);
    return $paginator;

This returns the paginator but the data is the same - meaning the same result set as without the paginator, when I'd expect only one record to be returned per page: 这将返回分页器,但数据是相同的-意味着与不使用分页器时相同的结果集,当时我希望每页仅返回一条记录:

    [{
    "total": 3,
    "per_page": 1,
    "current_page": 1,
    "last_page": 3,
    "next_page_url": "/?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 3,
    "data": {
        "data" : ".. same as above"
    }
}]

With aggregates you need to implement your own custom paginator, as stated by docs : 对于聚合,您需要实现自己的自定义分页器,如docs所述

Note: Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. 注意:目前,使用Laravel无法有效执行使用groupBy语句的分页操作。 If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually. 如果需要使用具有分页结果集的groupBy,建议您查询数据库并手动创建分页器。

See this posts to manually implement pagination: 请参阅以下帖子以手动实现分页:

Laravel 5 - Manual pagination Laravel 5-手动分页

Manually Creating a Paginator (Laravel 5) 手动创建分页器(Laravel 5)

Many people have pointed me to a widely mentioned paragraph in the Laravel documentation, 许多人向我指出了Laravel文档中广泛提及的一段,

Note: Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. 注意:目前,使用Laravel无法有效执行使用groupBy语句的分页操作。 If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually. 如果需要使用具有分页结果集的groupBy,建议您查询数据库并手动创建分页器。

Not terribly helpful, since I cannot find any example in the documentation as to exactly how to create a manual paginator using the results of an Eloquent query. 并不是很有帮助,因为我无法在文档中找到任何有关如何使用Eloquent查询结果创建手动分页器的示例。 So, here is what I was able to come up with. 因此,这就是我能想到的。 Note that you must use ->take() and ->offset() in the query, otherwise you will end up with the same results on every page (this is where I was getting stuck). 请注意,您必须在查询中使用->take()->offset() ,否则最终将在每个页面上得到相同的结果(这就是我被困住的地方)。

<?php
// routes.php
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
    get('test', function(Request $request) {
        $page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
        $numPerPage = 2; // Number of results per page
        $eventType = EventType::find(1); // Not relevant to pagination
        $count = $eventType->memberEvents()->count(); // Get the total number of entries you'll be paging through
        // Get the actual items
        $events = $eventType->memberEvents()->orderBy('start', 'asc')
            ->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($date) {
            return $date->start->format('F, Y');
        });
        // Create the paginator with Illuminate\Pagination\LengthAwarePaginator as Paginator
        // Pass in the variables supplied above, including the path for pagination links
        $paginator = new Paginator($events, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
        return $paginator;
    });

As stated in the Laravel docs...Note: Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. 如Laravel文档中所述...注意:当前,使用groupBy语句的分页操作无法由Laravel有效执行。 If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually. 如果需要使用具有分页结果集的groupBy,建议您查询数据库并手动创建分页器。 Docs 文件

If you want to add groupBy to your data the you should use LengthAwarePaginator object as updated in laravel 5 如果要将groupBy添加到数据,则应使用Laravel 5中更新的LengthAwarePaginator对象

Try this, 尝试这个,

use Illuminate\Pagination\LengthAwarePaginator as Paginator;

$page       = ($request->input('page') != null) ? $request->input('page') : 1;
$perPage    = 1;

$sliced     = array_slice($data, 0, 5); //you can these values as per your requirement 

$paginator  = new Paginator($sliced, count($data), $perPage, $page,['path'  => url()->current(),'query' => $request->query()]);

return $paginator;

$data is your data object and fifth parameters are for next and prev urls $ data是您的数据对象,第五个参数用于下一个和上一个网址

Refer this for more information about paginator, https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html#method_paginate 请参阅此以获取有关分页器的更多信息, https: //laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html#method_paginate

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

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