简体   繁体   English

如何在laravel应用程序中按hasMany相关表列的总和对结果进行排序

[英]How to order results by sum of a hasMany related table column in a laravel app

I am trying to order my API results by the sum of a hasMany relationship column in a laravel app.我正在尝试通过 laravel 应用程序中 hasMany 关系列的总和来排序我的 API 结果。 I'm trying to order my results by the sum of the count column in plays table so songs with the most plays appear first.我正在尝试按播放表中计数列的总和对结果进行排序,以便播放次数最多的歌曲首先出现。 I've seen other SO answers but they mainly deal with count and not sum.我看过其他 SO 答案,但它们主要处理计数而不是总和。 My setup is我的设置是

Tables

Songs歌曲

id
name

Plays戏剧

date
count
song_id

Models楷模

Song.php歌曲.php

public function plays()
{
    return $this->hasMany('App\Models\Play');
}

Play.php播放.php

public function song()
{
    return $this->belongsTo('App\Models\Song');
}

Contoller.php控制器.php

// Works
// $songs = Song::withSum('plays', 'count')->paginate(10);

// Does not work with orderBy.
$songs = Song::withSum('plays', 'count')->orderBy('plays_sum_count', 'desc')->paginate(10);

If I remove the orderBy from the above piece of code in the controller I get an array of songs with the plays_sum_count value set correctly but when I try to order it the request keeps running(in postman) resulting in an eventual timeout.如果我从控制器中的上面一段代码中删除 orderBy,我会得到一个正确设置 play_sum_count 值的歌曲数组,但是当我尝试对其进行排序时,请求继续运行(在邮递员中)导致最终超时。

How can I get a result set ordered by the sum of the count column in plays?如何获得按播放中计数列的总和排序的结果集?

try group your result then order them by the sum:尝试对您的结果进行分组,然后按总和对它们进行排序:

$songs = Song::join('plays','plays.soung_id','=','songs.id')->select('songs.*')->groupBy('songs.*')
->orderByRaw('SUM(plays) DESC')>paginate(10);

please pay attention to the table names请注意表名

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

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