对分组查询分页

时间:2019-03-24 20:05:55

标签: laravel date group-by pagination

我正在编写一个跟踪现金流的系统。用户注册他们进行的交易: (transactions index screenshot) 但我需要按日期分开进行这些交易。我尝试使用“请求索引”,但是它看起来并不是最好的做法(但是,它确实起作用了)。现在,我正在尝试另一个方法:检索所有交易并按日期对它们进行分页。有可能吗?

ps:也许按月分组有助于?喜欢:

$transactions = Transaction::all()->groupBy(function($transaction) {
    return Carbon::parse($transaction->date)->format('m-Y');
});

这将返回:

{
    "03-2019": [
        {
            "id": 1,
            "title": "Teste 1",
            "date": "2019-03",
            "user_id": 1,
            "description": "Primeiro teste, com entrada de 1500 reais.",
            "value": "1500.00",
            "flow": 1,
            "created_at": "2019-03-24 05:39:45",
            "updated_at": "2019-03-24 05:39:45"
        },
        {
            "id": 2,
            "title": "Teste 2",
            "date": "2019-03",
            "user_id": 1,
            "description": "Segundo teste, com saída de 500 reais.",
            "value": "500.00",
            "flow": 0,
            "created_at": "2019-03-24 05:39:45",
            "updated_at": "2019-03-24 05:39:45"
        }
    ]
}

ps²:是的,前端使用巴西葡萄牙语,而英语不是我的母语。.:)

1 个答案:

答案 0 :(得分:0)

尝试一下

<?php 

use Illuminate\Pagination\LengthAwarePaginator;

$transactions = Transaction::all()->groupBy(function($transaction) {
  return Carbon::parse($transaction->date)->format('m-Y'); 
});

//new LengthAwarePaginator($data,$countOfData,$perPage,$currentPage);
$transactions=new LengthAwarePaginator($transactions->forPage($currentPage,$perPage),$transactions->count(),$currentPage);

希望有帮助...