Reputation: 101
I have query in my BlogSearch where i join relation with User. In my Column User I want to searchin User by his fullname. This is my code of BlogSearch.
$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]);
Upvotes: 2
Views: 1450
Reputation: 133380
In your model Blog add a getter for fullName
public function getFullName() {
return $this->relUser.>Name . ' ' . $this->relUser.Surname;
}
Add to your BlogSearc a field for filter
class BlogSearch extends Blog
{
public $fullName;
/* setup rules */
public function rules() {
return [
/* your other rules */
[['fullName'], 'safe']
];
}
then use this for query instead of your JoinWith
$query->joinWith(['relUser' => function ($q) {
$q->where( 'UrUser.Name LIKE "%' .$this->fullName . '%"' . ' OR UrUser.Name LIKE "%' . $this->fullName . '%"' );
}]);
and in your gridView you can use directly the fullName field
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'Title',
'Description',
'fullName',
//'CreatedAt',
// 'IsDeleted',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
For Name and Surname in the same time try adding
->orFilterWhere(['like', 'concat(UrUser.Name, " " , UrUser.Surname) ', $this->fullName]);
Upvotes: 6
Reputation: 405
Try something like
$query->select('id, CONCAT_WS(' ', Name, Surname) as name')
->from('customer')
->where('CONCAT_WS(' ', Name, Surname) LIKE "%' . $search .'%"')
->limit(10)
Upvotes: 0