Group By eloquent laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39738774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:31:32  来源:igfitidea点击:

Group By eloquent laravel

sqllaraveleloquent

提问by Steve

I have all the matches ordered by start_date, but i want the date not to be shown always instead separate the teams by date like below:

我有按 start_date 排序的所有比赛,但我希望不总是显示日期,而是按日期将球队分开,如下所示:

$matches=Match::orderBy('start_date','desc')->get();
foreach($matches as $match)
{
      $match->team1;
      $match->team2;
      $match->start_date;
}

this gives:

这给出:

Team1
Team2 
2016-9-28
Team3
Team4 
2016-9-28
Team5
Team6 
2016-9-28
...

Instead I want

相反我想要

2016-9-28 
Team1
Team2 
Team3
Team4
Team5
Team6
....

2016-9-29
Team1
Team2
Team3
....

group_by start_date may be?

group_by start_date 可能是?

回答by chanafdo

Use groupByto group the resulting collection.

用于groupBy对结果集合进行分组。

$matchGroups = Match::orderBy('start_date','desc')->get()->groupBy('start_date');

If start_dateis a Carbon date you may try

如果start_date是碳日期,您可以尝试

$matchGroups = Match::orderBy('start_date','desc')->get()->groupBy(function($item) {
    return $item->start_date->format('Y-n-j');
});

And in your view

在你看来

@foreach ($matchGroups as $startDate => $matches) {
    {{ $startDate }}

    @foreach ($matches as $match) {
        {{ $match->team1 }}
        {{ $match->team2 }}
    @endforeach
@endforeach

回答by Jason Seah

hmm.. you can try

嗯..你可以试试

$matches =  Match::select(DB::raw('GROUP_CONCAT(team) AS teammate'), 'start_date')
           ->groupBy('start_date');
           ->get()
           ->toArray();

toArray is optional and the result should be:

toArray 是可选的,结果应该是:

array:2 [
    0 => array:2 [
      "start_date" => "2016-9-28"
      "teammate" => "Team1,Team2, Team3, Team4, Team5, Team6"
    ]
    1 => array:2 [
      "start_date" => "2016-9-29"
      "teammate" => "Team1,Team2, Team3"
    ]
]

is this the result you seeking for ?

这就是你想要的结果吗?