【问题标题】:Yii2 where condition with concatYii2 where条件与concat
【发布时间】:2016-07-01 12:44:50
【问题描述】:

我在使用全名自动完成时遇到问题。 我有一个用户表,其中包含名字、姓氏列。通过 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(); 

【问题讨论】:

  • This 可能会有所帮助...

标签: php yii2


【解决方案1】:

以下代码在我使用 SQL 数据库时运行良好

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

【讨论】:

  • 但只是 "CONCAT(staff.name, ' ',staff.surname,' ', staff.patronymic)" 没有括号
【解决方案2】:

你可以用

代替两个 orWhere 来代替名字和姓氏
    ->orWhere(" concat('firstname', ' ' ,  'lastname')  like concat('%',:search_term) ")
    ->addParam(':search_term',$searchTerm )

【讨论】:

  • 这里可以进行 SQL 注入。
  • @cronfy 相关的 $searchTerm 通常已经检查了 Yii2 框架是否避免 sqlinjection .. 出于多种原因.. 问题是关于构建适当的 concat 过滤器的方式..
  • 这不是正确的做法,因为它不安全。即使在您的上下文中它是安全的,如果将您的代码复制到另一个环境或另一个用例,它也会导致 sql 注入。最好使用他在问题更新中发布的作者自己的解决方案。
  • @cronfy 答案仅与问题有关.. OP 使用这种 vars 并回答,如果只是为了建议使用 concat 的正确方法.. 否则会有数千个问题批评者的每个答案..如果你想理解..好吧..否则..我无能为力。你..正确的方法是发布正确的答案..(我没有看到你回答..在这里)
  • 在 Yii2 中也是不安全的。
猜你喜欢
  • 2014-10-04
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多