如何在 Eloquent Query Builder (Laravel 4) 中按“SUM”排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20697019/
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 08:47:02  来源:igfitidea点击:

How to Order By "SUM" in Eloquent Query Builder (Laravel 4)

mysqlsqllaravellaravel-4eloquent

提问by user1072337

I have a table that has a relationship for artists that have been "liked". I.e. something like this:

我有一个表,它与“喜欢”的艺术家有关系。即这样的事情:

artists_id   fan_id  
1            1
1            2
1            3
4            1
4            2

There are tables "artists" and "fans" that contain the info for those entities. I would like to order the results of a query by the sum of the users that have liked an artist in Eloquent query builder in Laravel 4 (i.e. grouping results by count and then ordering them by count desc). And I would like to pull the artist information.

有包含这些实体信息的“艺术家”和“粉丝”表。我想按照在 Laravel 4 中的 Eloquent 查询构建器中喜欢艺术家的用户总数对查询结果进行排序(即按计数对结果进行分组,然后按计数 desc 对其进行排序)。我想拉艺术家信息。

This is what I have:

这就是我所拥有的:

$artists_most_popular = DB::table('artists')
                        ->join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
                        ->orderBy('sum('fanartists.fan_id')')
                        ->groupBy('artists.id')
                        ->take(50)
                        ->get();

        return $artists_most_popular;

I know this isn't right, but I'm at a loss as to how to structure this in eloquent. Any ideas? Thank you.

我知道这是不对的,但我不知道如何以雄辩的方式构建它。有任何想法吗?谢谢你。

回答by Robbo

Try DB::rawin the orderBy. So your example would be...

尝试DB::raworderBy。所以你的例子是......

$artists_most_popular = DB::table('artists')
                    ->join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
                    ->orderBy(DB::raw('sum(\'fanartists.fan_id\')'))
                    ->groupBy('artists.id')
                    ->take(50)
                    ->get();

return $artists_most_popular;