首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Laravel OrderBy关系计数

Laravel OrderBy关系计数
EN

Stack Overflow用户
提问于 2014-06-13 23:04:57
回答 7查看 54.7K关注 0票数 72

我正在尝试获得最受欢迎的黑客马拉松,这需要按相应的黑客马拉松的partipants->count()排序。抱歉,如果这有点难以理解的话。

我有一个数据库,格式如下:

代码语言:javascript
复制
hackathons
    id
    name
    ...

hackathon_user
    hackathon_id
    user_id

users
    id
    name

Hackathon模型是:

代码语言:javascript
复制
class Hackathon extends \Eloquent {
    protected $fillable = ['name', 'begins', 'ends', 'description'];

    protected $table = 'hackathons';

    public function owner()
    {
        return $this->belongsToMany('User', 'hackathon_owner');
    }

    public function participants()
    {
        return $this->belongsToMany('User');
    }

    public function type()
    {
        return $this->belongsToMany('Type');
    }
}

并且HackathonParticipant被定义为:

代码语言:javascript
复制
class HackathonParticipant extends \Eloquent {

    protected $fillable = ['hackathon_id', 'user_id'];

    protected $table = 'hackathon_user';

    public function user()
    {
        return $this->belongsTo('User', 'user_id');
    }

    public function hackathon()
    {
        return $this->belongsTo('Hackathon', 'hackathon_id');
    }
}

我尝试过Hackathon::orderBy(HackathonParticipant::find($this->id)->count(), 'DESC')->take(5)->get());,但我觉得我犯了一个大错误(可能是$this->id),因为它根本不起作用。

我该如何去尝试获得最受欢迎的黑客松,这是基于最高数量的相关hackathonParticipants?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2014-06-13 23:28:34

编辑:如果使用Laravel 5.2或更高版本,请使用kJamesy的答案。它的性能可能会更好一些,因为它不需要将所有参与者和黑客马拉松加载到内存中,只需要加载分页的黑客马拉松和这些黑客马拉松的参与者数量。

您应该能够很容易地使用CollectionsortBy()count()方法来完成这项工作。

代码语言:javascript
复制
$hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)
{
    return $hackathon->participants->count();
});
票数 44
EN

Stack Overflow用户

发布于 2016-10-13 20:36:54

这在Laravel 5.3中适用,使用您的示例:

代码语言:javascript
复制
Hackathon::withCount('participants')->orderBy('participants_count', 'desc')->paginate(10); 

这样,就可以在查询中对其进行排序,并且分页效果会很好。

票数 224
EN

Stack Overflow用户

发布于 2017-10-17 09:19:58

另一种方法是使用withCount()方法。

代码语言:javascript
复制
Hackathon::withCount('participants')
        ->orderBy('participants_count', 'desc')
        ->paginate(50);

参考:https://laravel.com/docs/5.5/eloquent-relationships#querying-relations

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

https://stackoverflow.com/questions/24208502

复制
相关文章

相似问题

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