defaultScope() + CDbCriteria() = ambiguous columns

I’ve got a defaultScope() for each model so that only the users rows are returned, eg:




public function defaultScope()

{         

	if (Yii::app()->user->isAdmin())

	{

		// Admins can see all records

		return array(

			'condition'=>'(TRUE)',

		);

	}

	else

	{

		// Only list the users own records

		return array(

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

		);     

	}

}



But if I use CDbCriteria() I get an error about user_id being an ambigious column.

Is there a way to prefix the user_id in the condition above with the alias depending on how its being called?

For example, if its being called by itself it should be ‘t.user_id’ but if its called by a CDbCriteria() and with() then it should be the name of the table in with, eg ‘withtablename.user_id’

Thanks, Russ

Try this:




public function defaultScope()

{

    return array(

        'alias'=>'someAlias',

        'condition'=>'someAlias.user_id=...',

    );

}



Another possible solution:




'condition' => $this->getTableAlias(false, false) . '.user_id = ...',



Brilliant! Thank you :)

Thanks a lot phtamas, you safe me from a lot of work! :)

excellent work phtamas… :)

Excellent phtamas !! :)