I did some further investigation.
Modified my models to define "preview" relation in Gallery instead of Photo:
As a result, Photo has no relations, while Gallery::relations returns following:
'preview' => array(self::HAS_MANY, 'Photo', 'gallery_id', 'limit' => 5, 'order' => 'RAND()'),
It seems using with() results in ignoring limit condition.
Following code does NOT apply limit (order however is applied):
$g = Gallery::model()->with(array('preview' => array('limit' => 5)))->findByPk(2);
foreach ($g->preview as $photo)
while this code does apply the limit:
$g = Gallery::model()->findByPk(2);
foreach ($g->preview as $photo)
Any suggestions?
Is that a bug?
SQL generated for each case:
first (incorrect):
SELECT `t`.`id` AS `t0_c0`, `t`.`title` AS `t0_c1`, `t`.`status` AS `t0_c2`, `t`.`author_id` AS `t0_c3`, `t`.`date_created` AS `t0_c4`, `t`.`description` AS `t0_c5`, `preview`.`id` AS `t1_c0`, `preview`.`filename` AS `t1_c1`, `preview`.`filename_original` AS `t1_c2`, `preview`.`gallery_id` AS `t1_c3`, `preview`.`user_id` AS `t1_c4`, `preview`.`date_added` AS `t1_c5`, `preview`.`order` AS `t1_c6` FROM `galleries` `t` LEFT OUTER JOIN `photos` `preview` ON (`preview`.`gallery_id`=`t`.`id`) WHERE (`t`.`id`=2) ORDER BY RAND()
second (correct)
SELECT `preview`.`id` AS `t1_c0`, `preview`.`filename` AS `t1_c1`, `preview`.`filename_original` AS `t1_c2`, `preview`.`gallery_id` AS `t1_c3`, `preview`.`user_id` AS `t1_c4`, `preview`.`date_added` AS `t1_c5`, `preview`.`order` AS `t1_c6` FROM `photos` `preview` WHERE (`preview`.`gallery_id`=:ypl0) ORDER BY RAND() LIMIT 5. Bound with :ypl0='2')
SELECT * FROM `galleries` `t` WHERE `t`.`id`=2 LIMIT 1