scopes with relations


I’m a beginner with Yii framework and I’m still trying to understand the Active Record relational model.

I have 2 tables A and B.

class A extends CActiveRecord



	public function relations() {

		return array(

			'allB' => array(self::HAS_MANY, 'B', 'id'),





class B extends CActiveRecord



    public function scopes() {

        return array(


                'condition'=>'date >= NOW()',






I’m trying to access all the B for today, using the scope with the relational attribute:


But it’s not working.

Check the Guide:


I already saw it, but it’s not very clear.

Should I use the ‘with’ option?

With the call?


Or the relation?

'allB' => array(self::HAS_MANY, 'B', 'id', 'with'=>'today')

I think firth case



returns an array of models, so you can’t apply any scopes to it. The only option is to use:


Yes, but with this solution I can’t use 2 different scopes in the same A loop:

eg. allB:today and allB:yesterday ?


Multiple scopes get AND combined, though.

Yes, but with this, I can’t loop on them separately.

But I think I found a solution (in the page comments) using this:




Since Yii 1.1.9 relations can be defined with scopes: See here

Is there any way of applying scopes to pre-determined set of relations?

For instance, in the classic Yii blog example, let’s assume I have a $currentpost variable holding a Post AR object. $currentpost->comments holds an array of Comment AR objects, which has a “recent” scope stating the comment was published in the last 24h.

Is there any way of getting only the "recent" comments for a post? Something like



have you tried:

$currentpost->comments( array( 'scopes'=>array( 'recent' ) ) );

should work in Yii >= 1.1.9 (I think in this version scopes were added to CDbCriteria object). Above line gets objects from defined relation and applies additional criteria defined by array (such call was possible even earlier but no scopes could be specified in criteria).

Wow, that was both very quick and accurate! :D

Thanks a lot!