scopes with relations

Hello,

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(

            'today'=>array(

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

            ),

        );

    }

...

}

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


A::model()->allB->today();

But it’s not working.

Check the Guide: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes

Thanks,

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

Should I use the ‘with’ option?

With the call?


A::model()->with('allB:today')->findAll();

Or the relation?


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

I think firth case


A::model()->with('allB:today')->findAll();




A::model()->allB;



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




A::model()->with('allB:today')->findAll();



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

eg. allB:today and allB:yesterday ?




A::model()->with('allB:today:yesterday')->findAll();



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:




A::model()->allB(allB:today)

and

A::model()->allB(allB:yesterday)



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


$currentpost->comments(":recent")

?

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!