簡體   English   中英

Yii2 條件與 concat

[英]Yii2 where condition with concat

我對全名自動完成有疑問。 我有一個用戶表,其中包含名字、姓氏列。到 ajax。

在搜索操作中,這是我的代碼:

$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(); 

以下代碼對我使用SQL數據庫的工作正常

$query->orWhere(['like', "CONCAT([staff].[first_name], ' ',[staff].[middle_name],' ', [staff].[last_name])", $this->name]);
$query->where([
              'OR',
              [
                  'like', 'program.program_code', $this->program_id
              ],
              [
                  'like', 'program.title', $this->program_id
              ],
              [
                  'like',
                  "CONCAT(program.program_code, '-' ,program.title )",
                  $this->program_id
              ]
          ]);
              [
                  'like',
                  "CONCAT(program.program_code, '-' ,program.title )",
                  $this->program_id
              ]

上面的代碼部分將幫助您准確地獲得您想要的。 我有點晚了,但它可能會幫助未來的新人。 您也可以閱讀文檔以更好地理解https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#building-queries

可以用“ where”代替“ orname”和“ lasta name”

    ->orWhere(" concat('firstname', ' ' ,  'lastname')  like concat('%',:search_term) ")
    ->addParam(':search_term',$searchTerm )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM