[SOLVED] MANY_MANY filtered relational AR query

Let’s say you need to populate a CActiveDataProvider in an action method of a controller class with the results of a filtered MANY_MANY relation.

For example, you might do this prior to rendering the index view from the ThingController to limit the Things being displayed to only those Things that have been assigned to the current user.

In this example our models would be User.php and Thing.php

We would have 3 relevant tables, in the database, together with their respective primary and foreign keys.

tbl_thing <- with PK id

tbl_user <- with PK id

tbl_thing_user <- with PK id, FK (thing.id, user.id)

One table for each of the two models,(Thing, and User) and a third relations table ( tbl_thing_user)

You also need to ensure that the relations() method in model Thing.php is set up to reference the relation with the Users model like so…





public function relations()

	{

  	...

		return array(

   		...

			'users' => array(self::MANY_MANY, 'User', 'tbl_thing_user(thing_id,user_id)'),

		);

	}









this code works on 1.1.8


   public function actionIndex()

	{   		

           	//set up a new data provider instance used to pass Thing:: data into the index view.   

       		$dataProvider=new CActiveDataProvider('Thing');

            	

          	//create a filter

                	$things=Thing::model()->with(array(

                    	'users'=>array(

                        	'select'=>false,

                        	'joinType'=>'INNER JOIN',

                        	'condition'=>'users.id='.Yii::app()->user->id,

                    	)

                	))->findAll();

                	

                	//re-initialize the dataProvider with authorized data

                	$dataProvider->setData($things);


           		//then render the view with the filtered data

           		$this->render('index',array(

	                	'dataProvider'=>$dataProvider,

           		));


 	}