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

问题描述

我试图获得最受欢迎的黑客攻击,需要通过相应的hackathon的 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.

我将如何去尝试最受欢迎的hackathons是基于相关的hackathonParticipants数量最多的人?

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

推荐答案

您应该可以使用集合 sortBy() 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关系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:10