我试图获取最流行的黑客马拉松,需要按照各自黑客马拉松的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),因为它根本不起作用。
我该如何获取与最高数量的相关 hackathonParticipants 基于最受欢迎的 hackathons?
withCount()
方法。 - Marek SkibamaleParticipants
,则查询应该像这样withCount('maleParticipants')->orderBy('male_participants', 'desc')
。 - Syamsoul Azrien$this->crud->query->withCount('contactTags')->orderBy('contact_tags_count', 'desc')
。 - Ryan->orderByDesc('participants_count')
可以使订单查询更加优雅。 - Muh Ghazali Akbar