我在我的博客搜索中有查询,我在其中加入了与用户的关系。在我的列用户中,我想按他的全名搜索用户。这是我的博客搜索代码。
$query->joinWith('relUser');
$query->andFilterWhere([
'Id' => $this->Id,
'CreatedAt' => $this->CreatedAt,
]);
$query->andFilterWhere(['like', 'Title', $this->Title])
->andFilterWhere(['like', 'Description', $this->Description])
->andFilterWhere(['like', 'User.Name', $this->Rel_User])
->andFilterWhere(['like', 'User.Surname', $this->Rel_User]);
在您的模型博客中添加一个 getter for fullName
public function getFullName() {
return $this->relUser.>Name . ' ' . $this->relUser.Surname;
}
将过滤器字段添加到您的博客Searc
class BlogSearch extends Blog
{
public $fullName;
/* setup rules */
public function rules() {
return [
/* your other rules */
[['fullName'], 'safe']
];
}
然后使用它进行查询,而不是您的 JoinWith
$query->joinWith(['relUser' => function ($q) {
$q->where( 'UrUser.Name LIKE "%' .$this->fullName . '%"' . ' OR UrUser.Name LIKE "%' . $this->fullName . '%"' );
}]);
在网格视图中,您可以直接使用 fullName 字段
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'Title',
'Description',
'fullName',
//'CreatedAt',
// 'IsDeleted',
['class' => 'yii'grid'ActionColumn'],
],
]); ?>
对于同时的姓名和姓氏,请尝试添加
->orFilterWhere(['like', 'concat(UrUser.Name, " " , UrUser.Surname) ', $this->fullName]);
尝试类似
$query->select('id, CONCAT_WS(' ', Name, Surname) as name')
->from('customer')
->where('CONCAT_WS(' ', Name, Surname) LIKE "%' . $search .'%"')
->limit(10)