Laravel eloquent统计一个特定事件所属部门的参与者总数



我的当前查询可以统计属于每个部门的参与者人数:

$departments = Department::select(['departments.id', 'departments.name'])
->with('participants')
->withCount('participants')
->orderByDesc('participants_count')
->groupBy('departments.name')
->groupBy('departments.id')
->get();

我有一个表departments和另一个表participants。在参与者表中,有fk_key称为department_id,当一个参与者开始注册时,我需要选择他的部门。

在模型Department中,我有一个hasManyParticipant的关系:

public function participants() {
return $this->hasMany(Participant::class, 'department_id');
}

使用这个关系,我可以执行上面的查询,我得到这样的东西:

#DepartName   #participants_count
department_1  12
department_2  5
department_3  44
department_4  33
这里对我来说没有问题。但问题就在这里。首先,在我的数据库中存在一个名为events的表和另一个名为event_participant的表。我可以注册事件,在一个数据透视表event_participant中,我可以注册事件的参与者,并控制每个事件参与者的支付状态。

数据透视表有如下列:

event_participant

id  | event_id  | participant_id | payment_state

我的模型Event有一个叫做participants的关系,使用这个关系我可以得到属于每个事件的所有参与者。

public function participants() {
return $this->belongsToMany(Participant::class, 'event_participant',
'event_id',
'participant_id')
->withTimestamps();
}

现在我想统计每个部门的参与者总数,就像上面的查询一样,但是要统计一个特定的事件。

例如:存在两个事件,第一个事件注册了10个参与者,这10个参与者中5个属于部门A, 5个属于部门B,所有这些参与者都属于事件1。在我的数据库中存在5个部门对于事件1,我应该得到这样的内容:

#departName     #participants_count
department_A    5
department_B    5
department_C    0
department_D    0
department_E    0

此报告仅适用于事件。我的想法是让所有的部门与他的参与者总数xevent。为了将参与者注册到事件,我使用了一个名为event_participant的数据透视表。

。我在Event,DepartmentParticipant模型上使用软删除。

您可以为withCount添加额外的约束。

我跳过了你原始查询的其他部分。

$eventName = 'xyz';
$departments = Department::withCount(['participants' => function ($query) use ($eventName) {
$query->whereHas('events', function ($query) use ($eventName) {
$query->where('name', $eventName);
});
}])->orderByDesc('participants_count')->get();

https://laravel.com/docs/8.x/eloquent-relationships counting-related-models

最新更新