I have a user model that HAS_MANY posts. In the user list, I would like to display the number of posts each user has. All works fine, but the generated SQL looks inefficient and unclean.
<?php //User model: public function relations() { return array( 'post' => array(self::HAS_MANY, 'Post', 'user_id'), 'num_posts' => array(self::STAT, 'Post', 'user_id'), ); } //relevant controller snippet $users=User::model()->with('group', 'num_posts')->findAll($criteria); //generated SQLs 1. SELECT `user`.`id` AS t0_c0, `user`.`username` AS t0_c1, `user`.`password` AS t0_c2, `user`.`email` AS t0_c3, `user`.`email_visible` AS t0_c4, `user`.`notify_comments` AS t0_c5, `user`.`notify_messages` AS t0_c6, `user`.`about` AS t0_c7, `user`.`aboutParsed` AS t0_c8, `user`.`group_id` AS t0_c9, `user`.`email_confirmed` AS t0_c10, `user`.`created` AS t0_c11, `user`.`modified` AS t0_c12, t1.`id` AS t1_c0, t1.`name` AS t1_c1 FROM `user` LEFT OUTER JOIN `group` t1 ON `user`.`group_id`=t1.`id` ORDER BY `user`.`created` DESC LIMIT 25 2. SELECT `user_id` AS c, COUNT(*) AS s FROM `post` GROUP BY `user_id` HAVING `post`.`user_id` IN (105, 103, 102, 1, 101, 78, 56, 67, 66, 89, 86, 65, 52, 93, 79, 41, 58, 51, 76, 88, 46, 57, 80, 72, 82)
Using the IN() functions seems much less efficient then a simple JOIN. Shouldn't it JOIN it instead? (using together() gives the same result)
Also, I have not tried or tested this yet, but do you think it would be possible to sort a user list by the number of posts a user has created?