You need to do in one query count and sum. The query is something like this:
UsersPays::find() ->where([ 'and', ['=', 'users_pays.status', '1'], ['=', 'users_pays.active', '1'], ['=', 'users_pays.pay_type_id', '1'], ]) ->groupBy('users_pays.card_id') Now the most interesting thing: if I add to the request ->count('users_pays.id') or ->sum('users_pays.money) then everything is fine. but it turns out two requests. yii generates something like this:
SELECT COUNT(*) FROM (SELECT `users_pays`.* FROM `users_pays` WHERE (`users_pays`.`status` = '1') AND (`users_pays`.`active` = '1') AND (`users_pays`.`pay_type_id` = '1') GROUP BY `users_pays`.`card_id`) `c` when I write in yii:
UsersPays::find() ->select('COUNT(users_pays.id) as count, SUM(users_pays.money) as sum') ->where([ 'and', ['=', 'users_pays.status', '1'], ['=', 'users_pays.active', '1'], ['=', 'users_pays.pay_type_id', '1'], ]) ->groupBy('users_pays.card_id') yii generates the following query:
SELECT COUNT(users_pays.id), SUM(users_pays.money) FROM `users_pays` WHERE (`users_pays`.`status` = '1') AND (`users_pays`.`active` = '1') AND (`users_pays`.`pay_type_id` = '1') GROUP BY `users_pays`.`card_id` in the answer comes not the amount and quantity for the whole table, but an array with the amount and quantity for each card_id
Tell me how to do it right?
->select(count...)works - Genius JokesΠ² ΠΎΡΠ²Π΅ΡΠ΅ ΠΏΡΠΈΡ ΠΎΠ΄ΠΈΡ Π½Π΅ ΡΡΠΌΠΌΠ° ΠΈ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΏΠΎ Π²ΡΠ΅ΠΉ ΡΠ°Π±Π»ΠΈΡΠ΅, Π° ΠΌΠ°ΡΡΠΈΠ² Ρ ΡΡΠΌΠΌΠΎΠΉ ΠΈ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²Ρ ΠΏΠΎ ΠΊΠ°ΠΆΠ΄ΠΎΠΌΡ card_idBy what you group, by that it groups. If it is necessary on the entire table - remove GROUP BY altogether or makeGROUP BY 1. - Akina