How To Access Related Model Object With Limit

I’ve two model class like A, B

A and B both has relation defined in model class like:




class A extends CActiveRecord {

  ...

  public function relations() {

	return array(

  	'b' => array(self::HAS_MANY, 'B', 'a_id'),

	);

  }

  ...

}


class B extends CActiveRecord {

  ...

  public function relations() {

	return array(

  	'a' => array(self::BELONGS_TO, 'A', 'a_id'),

	);

  }

  ...

}



Now I’m fetching all A using script:




$a = A::model()->findAll();



Then after I’m accessing all A’s related object of B, but I want only limited records, like just 4 B's for each A's:




foreach($a as $each_a) {

  $b = $each_a->b; // Want only 4 B's here

}



How can I access only 4 B’s records for each A’s




class A extends CActiveRecord {

    ...

    public function relations() {

       return array(

           'b' => array(self::HAS_MANY, 'B', 'a_id', 'limit' => 4),

       );

    }

    ...

}

...

foreach($a as $each_a) {

    foreach ($each_a->b as $each_<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='B)' /> {

        print_r($each_b->attributes);

    }

}



More details in Yii Guide: Working with Databases - Relational Active Record.

Or use this:;)




$a = A::model()->with(arrya(

        'B'=>array(

              'limit'=>4,

         ),

))->findAll();