2016-03-04 147 views
0

我在我的BlogSearch中查詢,我加入與用戶的關係。在我的專欄用戶中,我想通過他的全名搜索用戶。這是我的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]); 
+0

什麼意思不工作,,錯誤,,錯誤的結果?..請顯示所有的搜索模型 – scaisEdge

+0

我怎樣才能將我的列連接成一個? – qwerty

+0

你想在哪裏連接列,,, sqlquery? ,,, gridview列)?更正你的問題,並有適當的解釋,並顯示你的相關searchModel,controllerAction和查看請.. – scaisEdge

回答

3

在模型博客添加getter的全名

public function getFullName() { 
    return $this->relUser.>Name . ' ' . $this->relUser.Surname; 
} 

添加到您的BlogSearc一個字段過濾

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 . '%"'); 
     }]); 

,並在你的GridView可以在同一時間嘗試添加

->orFilterWhere(['like', 'concat(UrUser.Name, " " , UrUser.Surname) ', $this->fullName]); 
直接使用全名外地

<?= GridView::widget([ 
     'dataProvider' => $dataProvider, 
     'filterModel' => $searchModel, 
     'columns' => [ 
      'Title', 
      'Description', 
      'fullName', 
      //'CreatedAt', 
      // 'IsDeleted', 

      ['class' => 'yii\grid\ActionColumn'], 
     ], 
    ]); ?> 

對於名和姓

+0

我有數據庫異常:SQLSTATE [42S22]:未找到列:1054未知列'relUser 'Name'in'where clause' 正在執行的SQL是:SELECT COUNT(*)FROM'urBlog' LEFT JOIN'urUser' ON'urBlog'.'Rel_User' ='urUser'.'Id' WHERE relUser.Name LIKE 「%%」或者relUser.Surname LIKE「%%」這個異常是這個查詢的形式。你可以在這個查詢中告訴我'relUser.Name','relUser'是關係名稱或者表名嗎? – qwerty

+0

在$ query-> anWhere(...)中,您必須設置正確的表名...可能是UrUser ..我已更新答案.. – scaisEdge

+0

不幸的是,搜索不起作用時,我把一些字母它notting發生了 – qwerty

0

嘗試像

$query->select('id, CONCAT_WS(' ', Name, Surname) as name') ->from('customer') ->where('CONCAT_WS(' ', Name, Surname) LIKE "%' . $search .'%"') ->limit(10)