我有以下型号:
User
的列{ID,USER_NAME,密码,USER_TYPE}
Admin
的列{ID,USER_ID,FULL_NAME,.....等}
Editor
与列{ID,USER_ID,FULL_NAME,...等}
和关系是User
: 'admin' => array(self::HAS_ONE, 'Admin', 'user_id'),'editor' => array(self::HAS_ONE, 'Editor', 'user_id'),
Admin
: 'user' => array(self::BELONGS_TO, 'User', 'user_id'),
Editor
: 'user' => array(self::BELONGS_TO, 'User', 'user_id'),
现在,我有设置一个虚拟属性fullName
在User
模式,如下
public function getFullName()
{
if($this->user_type=='admin')
return $this->admin->full_name;
else if($this->user_type=='editor')
return $this->editor->full_name;
}
我可以显示虚拟属性, fullName
,在GridView,但我怎么一个过滤器添加到属性,使其在GridView排序?
UPADTE 1:
我更新了模型搜索()函数按照由@乔恩的答案如下图所示
public function search()
{
$criteria=new CDbCriteria;
$criteria->select=array('*','COALESCE( editor.full_name,admin.first_name, \'\') AS calculatedName');
$criteria->with=array('editor','admin');
$criteria->compare('calculatedName',$this->calculatedName,true);
$criteria->compare('email',$this->email,true);
$criteria->compare('user_type',$this->user_type);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
这两个管理员和编辑的名称在GridView正确显示。 但是,当我通过以下发生异常过滤器进行搜索,
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'calculatedName' in 'where clause'. The SQL statement executed was: SELECT COUNT(DISTINCT `t`.`id`) FROM `user` `t` LEFT OUTER JOIN `editor` `editor` ON (`editor`.`user_id`=`t`.`id`) LEFT OUTER JOIN `admin` `admin` ON (`admin`.`user_id`=`t`.`id`) WHERE (calculatedName LIKE :ycp0) (C:\xampplite\htdocs\yii\framework\db\CDbCommand.php:528)</p><pre>#0 C:\xampplite\htdocs\yii\framework\db\CDbCommand.php(425):
我怎样才能摆脱呢?
更新2:我的错误。 它工作正常,当我改了行
$criteria->compare('calculatedName',$this->calculatedName,true);
至
$criteria->compare('COALESCE( editor.full_name,admin.first_name, \'\')',$this->calculatedName,true);
和BTW感谢名单@乔恩。