Laravel eloquent 计算属于某个特定事件的部门的参与者总数

Laravel eloquent count total of participants that belongs to departments of one specific event

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

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

我有一个 table departments 和另一个 participants。在参与者 table 中有 fk_key 被称为 department_id 当一个参与者正在注册时我需要 select 他的部门。

在模型中 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 的 tabla 和另一个名为 event_participant 的 table。 我可以注册事件,并且在一个数据透视表中 table event_participant 我可以将参与者注册到事件中并控制每个事件参与者的支付状态。

这个数据透视 table 有这些列:

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 个部门 对于事件一的这个示例,我应该得到这样的信息:

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

此报告仅针对事件一。我的想法是让所有部门的参与者总数为 x event。为了将参与者注册到事件中,我使用了一个名为 event_participant.

的枢轴 table

注意。我在 EventDepartmentParticipant 模型上使用软删除。

您可以向 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