我當前的查詢可以統計屬于每個部門的參加人數:
$departments = Department::select(['departments.id', 'departments.name'])
->with('participants')
->withCount('participants')
->orderByDesc('participants_count')
->groupBy('departments.name')
->groupBy('departments.id')
->get();
我有一張桌子departments,另一個叫participants. 在參與者表中,department_id當一個參與者開始注冊時,以這種方式呼叫fk_key 我需要選擇他的部門。
在模型內部,Department我hasMany與Participant:
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
這里對我來說沒有問題。但是問題就來了。首先,在我的資料庫中存在一個名為的 tablaevents和另一個名為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 個部門 I對于事件一的這個例子,應該得到這樣的東西:
#departName #participants_count
department_A 5
department_B 5
department_C 0
department_D 0
department_E 0
我希望你能理解我,本報告僅針對事件之一。我的想法是讓所有部門與他的 x 參與者總數event。為了將參與者注冊到事件中,我使用了一個名為event_participant.
非常感謝。
筆記。我在Event,Department和Participant模型上使用了軟洗掉。
uj5u.com熱心網友回復:
您可以向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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/329917.html
