更新时间:2023-12-01 13:42:34
这应该可行,将其添加到search()方法中的搜索条件中:
This should work, add it to your search criteria in the search() method:
$criteria->with[]='user';
$criteria->addSearchCondition("user.secondname",$this->user_id);
这是我要做的:
if(!intval($this->user_id) && is_string($this->user_id) && strlen($this->user_id) > 0) {
$criteria->with[]='user';
$criteria->addSearchCondition("user.secondname",$this->user_id);
} else
$criteria->compare('t.user_id',$this->user_id);
这是CGridView定义:
And here is the CGridView definition:
'columns'=>array(
...
array(
'name' => 'user_id',
'header'=>'User',
'sortable'=>false, // since it would still be sorting based on ID
// 'value' => '$data->user->lastname', // basic version
'value'=>'CHtml::link((isset($data->user))?$data->user->username:$data->user_id,array("user/view","id"=>$data->user_id))', // link version
),
这是一个有趣的小技巧:如果搜索项是字符串而不是intval(),它将通过用户名通过用户的第二名来搜索用户.但是,如果输入user_id,它将通过用户的user_id(默认的search()功能)找到用户.
It's a fun little trick: if the search term is a string and NOT an intval(), it searches for the user by their secondname, via the "user" relation. But if you enter a user_id, it will find the user by their user_id - the default search() functionality.
注意:这将启用过滤功能,但仍会根据ID进行排序.您将需要实施一些其他操作才能使排序工作正常进行.
NOTE: This will enable filtering, but it will still sort based on ID. You will need to implement something additional to get the sorting to work.
当然还有其他方法可以做到这一点,但这就是我的方法.我怀疑使用该关系执行此操作是正确的",但是我的技术工作可靠.
There are surely other ways to do this, but this is how I do it. I suspect there is a "right" to do this using the relation, but my technique works solid.