Laravel OrderBy 关系计数 [英] Laravel OrderBy relationship count

查看:24
本文介绍了Laravel OrderBy 关系计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获得最流行的黑客马拉松,这需要通过相应的黑客马拉松的 partipants->count() 进行排序.对不起,如果这有点难以理解.

I'm trying to get the most popular hackathons which requires ordering by the respective hackathon's partipants->count(). Sorry if that's a little difficult to understand.

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

I have a database with the following format:

hackathons
    id
    name
    ...

hackathon_user
    hackathon_id
    user_id

users
    id
    name

Hackathon 模型是:

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定义为:

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),因为它根本不起作用.

I've tried Hackathon::orderBy(HackathonParticipant::find($this->id)->count(), 'DESC')->take(5)->get()); but I feel like I made a big mistake (possibly the $this->id), because it doesn't work at all.

我将如何尝试获得基于最多相关黑客马拉松参与者数量的最受欢迎的黑客马拉松?

How would I go about trying to get the most popular hackathons which is based on the highest number of related hackathonParticipants?

推荐答案

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

If using Laravel 5.2 or greater, use kJamesy's answer. It will likely perform a bit better because it's not going to need to load up all the participants and hackathons into memory, just the paginated hackathons and the count of participants for those hackathons.

您应该能够使用 CollectionsortBy()count() 方法来轻松完成此操作.>

You should be able to use the Collection's sortBy() and count() methods to do this fairly easily.

$hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)
{
    return $hackathon->participants->count();
});

这篇关于Laravel OrderBy 关系计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆