php - Laravel OrderBy 关系计数

标签 php mysql laravel eloquent

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

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

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

我将如何尝试根据最多的相关黑客松参与者获得最受欢迎的黑客松?

最佳答案

这适用于我在 Laravel 5.3 中,使用你的例子:

Hackathon::withCount('participants')->orderBy('participants_count', 'desc')->paginate(10); 

这样它在查询中被排序并且分页效果很好。

关于php - Laravel OrderBy 关系计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24208502/

相关文章:

没有 GROUP BY 子句的 MySQL 聚合函数

PHP - 严格的标准 : Only variables should be passed by reference

php - 提取后如何删除laravel delete文件?

php - 检查是否使用 Laravel 数据透视表设置了某些内容

php - 如何从多个表中获取结果

php - Laravel 验证规则 : required_without

php - 在 Laravel 中保存模型时直接设置 ID 和设置 Eloquent 关联关系的区别?

PHP 如何从数组中删除元素 - array_uniqe 不起作用

php - 如何将 mysql 表导出到 csv 文件并下载

php - 查询 3 个表和一个 MAX