2016-07-01 53 views
2

我有問題全名自動完成。 我有一個usertable,它包含firstname,lastname columns.through ajax。Yii2條件與concat

在搜索行動,這是我的代碼:

$users = (new Query()) 
       ->select('*') 
       ->from($userTable) 
       ->where(['like', 'username', $searchTerm]) 
       ->orWhere(['like', 'firstname', $searchTerm]) 
       ->orWhere(['like','lastname', $searchTerm])  
       ->andWhere(['<>','id', Yii::$app->user->id]) 
       ->andWhere(['status'=>self::STATUS_ACTIVE]) 
       ->orderBy('username') 
       ->limit(20) 
       ->all(); 

我的問題是,當我試圖用姓氏漸漸空虛記錄搜索名字。

感謝您的支持,我必須保持CONCAT

解決
$users = (new Query()) 
        ->select('*') 
        ->from($userTable) 
        ->where(['like', 'username', $searchTerm]) 
        ->orWhere(['like', "CONCAT(firstname, ' ', lastname)", $searchTerm]) 
        ->andWhere(['<>','id', Yii::$app->user->id]) 
        ->andWhere(['status'=>self::STATUS_ACTIVE]) 
        ->orderBy('username') 
        ->limit(20) 
        ->all(); 
+0

[This](http://stackoverflow.com/questions/31297668/yii2-gridview-merge-two-columns/3 8130105#38130105)可能會有幫助... –

回答

-2

可能是你可以用

->orWhere(" concat('firstname', ' ' , 'lastname') like '%" . $searchTerm . "' ") 
+1

SQL注入可能在這裏。 – cronfy

+0

@cronfy相關的$ searchTerm通常是用alireay檢查以避免Yii2框架的sqlinjection ..出於以下幾個原因..並且問題是關於如何構建適當的concat過濾器.. – scaisEdge

+1

這不是正確的方法,因爲它是不安全的。即使在您的上下文中它是安全的,但如果將代碼複製到另一個環境或另一個用例,它會導致sql注入。更好地使用他在問題更新中發佈的作者自己的解決方案。 – cronfy

0

下面的代碼工作正常,我替補多兩個orWhere的姓名和lasta名使用SQL數據庫

$query->orWhere(['like', "CONCAT([staff].[first_name], ' ',[staff].[middle_name],' ', [staff].[last_name])", $this->name]);