首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套约束groupBy加载并得到组的最后一项

嵌套约束groupBy加载并得到组的最后一项
EN

Stack Overflow用户
提问于 2022-06-04 16:05:30
回答 2查看 76关注 0票数 0

具有非功能约束的查询,以演示所要实现的内容。

代码语言:javascript
复制
public function readSongsVersions() 
{
   $data = Hierarchy::query()
           ->whereNull('parent_id')
           ->with(['children.song' => function ($query)  {
                    $query->groupBy('number')
                          ->orderBy('id', 'asc')
                          ->max('id') //this does not work
           }])
           ->get();
   }

歌曲表

代码语言:javascript
复制
   id  version  number
   1   AAA     1
   2   BBB     1
   3   CCC     1
   4   DDD     2
   5   EEE     3
   6   FFF     4
   7   GGG     4 

目标是只获得每首歌的最新版本。

歌曲1号有3个版本,最后一个版本是:id:3 with 版本:CCC

歌曲编号4有两个版本,最后一个版本是:id:7版本:GGG

预期歌曲版本结果

代码语言:javascript
复制
 CCC
 DDD
 EEE
 GGG
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-06-04 17:10:27

您可以尝试使用子查询来实现所需的输出。

代码语言:javascript
复制
//Assuming `child_id` is the foreign key on `songs` table 
//which references primary key `id` on `children` table

public function readSongsVersions()
{
    $data = Hierarchy::query()
        ->whereNull('parent_id')
        ->with([
            'children.songs' => function ($query) {
                $query->where('id', '=', function($query) {
                    $query->select(DB::raw('MAX(i.id)'))
                        ->from('songs as i')
                        ->whereRaw('i.number = songs.number')
                        ->whereRaw('i.child_id = songs.child_id');
                    });
            }
        ])
        ->get();
}

或者,如果您想不需要子查询就这样做的话

代码语言:javascript
复制
//Assuming `child_id` is the foreign key on `songs` table 
//which references primary key `id` on `children` table
public function readSongsVersions()
{

    //Get ids of songs which have the highest id for particular number and child_id
    //Means get the id of latest version of song for particular number 
    //within records of songs which belong to a particular children record
    $ids = Song::query()
        ->select(DB::raw('MAX(id) as id'), 'child_id', 'number')
        ->groupBy('child_id', 'number')
        ->get()
        ->pluck('id');

    //Then use these $ids to filter out the songs records
    $data = Hierarchy::query()
        ->whereNull('parent_id')
        ->with([
            'children.songs' => fn($query) => $query->whereIn('id', $ids)
        ])
        ->get();
}
票数 2
EN

Stack Overflow用户

发布于 2022-06-04 17:15:03

我想知道这在你的情况下是否有效。

代码语言:javascript
复制
$data = Hierarchy::select("version","number")
           ->whereNull('parent_id')
           ->withMax(children.song','id')
           ->get()
           ->toArray();

您应该在数组中包含类似song_version_max_id的内容。或者类似的,使用dd($data)查看结果。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72501230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档