About Gii generated function relations()

I notice that in the model class (generated by gii), there is a function as below. If I use XX->notes, I can get an array for a CArrayDataProvider. Now I can add ‘order’, but I want also add a condition for that, i.e. user_id=Yii::app()->user->id. Please how can I do that?




class XX extends CActiveRecord {


  public function relations() {

	return array(

		...

		'notes' => array(self::HAS_MANY, 'Note', 'module_id', 'order' => 'notes.create_at DESC'),

		...

	);

  }


}



ok, found the answer




'condition'=>'notes.user_id='.Yii::app()->user->id



Hope this could help others

But this seems not make sense. I mean, if I write this condition in the model class, I can only get the ‘notes’ from one user. (Am I right?) What if I want to get all the ‘notes’ from all users?

Can somebody help me with this?

Actually, I can use xx->notes to get an array, then to generate a CArrayDataProvider for CListView (or CGridView), so I am thinking whether I can add any conditions to CArrayDataProvider or CListView. Anyone has any ideas?????

Hi,

i think the simplest solution is to create two relations as follows:




class XX extends CActiveRecord {


  public function relations() {

        return array(

                ...

                'allNotes' => array(self::HAS_MANY, 'Note', 'module_id', 'order' => 'notes.create_at DESC'),

                'notes' => array(self::HAS_MANY, 'Note', 'module_id',  'condition'=>'notes.user_id='.Yii::app()->user->id, 'order' => 'notes.create_at DESC'),

                ...

        );

  }


}



So if you need notes for all users - just use $model->allNotes.

Please also read documentation for named scopes and relational ActiveRecord for developing more general solution.

Hope this will help.

Wow, that’s brilliant, thank you!