apply criteria condition on HAS_MANY

Sorry but I don’t know how to explain my problem.

I’ve a model Clan with many ClanAdmin

this is the relations:


public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'naz' => array(self::BELONGS_TO, 'Nazione', 'nazione_id'),

			'admins' => array(self::HAS_MANY, 'ClanAdmin', 'clan_id'),

		);

	}

and in the admin I want to take only the list of clans that can be managed by the current user.

ClanAdmin is composed by id, clan_id and user_id


public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;

		

		if ( !User::checkRole(User::ROLE_ADMIN) ) {

			$criteria->with='admins';

			$criteria->condition='admins.user_id=:userID';

			$criteria->params=array(':userID'=> User::getUserID());

			

		}


		$criteria->compare('nome',$this->nome,true);

		$criteria->compare('tag',$this->tag,true);

		$criteria->compare('status',$this->status);


		return new CActiveDataProvider('Clan', array(

			'criteria'=>$criteria,

		));

	}

This is the error: CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘admins.user_id’ in ‘where clause’

How can I do it? Thank you very much

Yii uses different aliases.

For the main table the alias is ‘t’, for all related table the alias is the name of the table itself, in your case AdminClan, not admins.

Anyway you can customize the aliases with the property ‘alias’ of CDbCriteria.

I am not sure that you have to explicitate


$criteria->condition='admins.user_id=:userID';

maybe Yii authomatically create this condition.

General advice: put this in your config.main




		'log'=>array(

			'class'=>'CLogRouter',

			'routes'=>array(

				array(

					'class'=>'CFileLogRoute',

					'levels'=>'error, warning',

				),

				array(

					'class'=>'CWebLogRoute',

					'levels'=>'trace',

				),/**/

			),



so you can check the queries created by yii.

http://www.yiiframework.com/forum/index.php?/topic/9714-sort-user-defined-column-in-cgridview/

http://www.yiiframework.com/forum/index.php?/topic/7420-undestanding-relational-queries-with-cactivedataprovider/

examples for sort and filter relational fields