Reputation: 3696
I'am working on two models.
Credentials model has a default scope method, where I've added addNotInCondition to filter blocked users. Here is my code
public function defaultScope() {
$criteria = new CDbCriteria();
$criteria->addNotInCondition("t.id", BanUser::model()->bannedUsers);
return $criteria;
}
This works fine. But While accessing credentials model from Messages model, it gives me error. Unknown column 't.id'. (BELONGS_TO relation is defined in messages model)
$message->credential; //this generate error.
What could be solution to this problem. I know this is due table aliases. I'm stuck here. Please help.
Upvotes: 4
Views: 3156
Reputation: 915
You can set table alias for model by its default scope method:
/**
* @return array default scope (applies only to SELECT statements)
*/
public function defaultScope () {
return array(
'alias' => $this->tableName(),
);
}
Then use alias elsewhere too, e.g. in search:
public function search () {
$criteria = new CDbCriteria;
$criteria->alias = $this->tableName();
$criteria->compare( $criteria->alias.'.id', $this->id );
return new CActiveDataProvider( $this, array(
'criteria' => $criteria,
) );
}
Upvotes: 3
Reputation: 1454
First of all, you can get current model alias name like this:
public function defaultScope() {
$alias = $this->getTableAlias(false,false);
$criteria = new CDbCriteria();
$banned = array();
foreach(BanUser::model()->bannedUsers as $user)
$banned[] = $user->id;
$criteria->addNotInCondition($alias.".id", $banned);
return $criteria;
}
Then I'm not sure about BanUser::model()->bannedUsers. Manual tells us that addNotInCondition accepts array (i.e. ('val1','val2','val3','etc')). If I remember well, relational fields aren't arrays of values, but are objects.
Upvotes: 2