【问题标题】:Cakephp 3 search query, with concatCakephp 3 搜索查询,带 concat
【发布时间】:2017-02-05 01:36:07
【问题描述】:

我正在尝试对两个连接列 fname 和 lname 执行搜索。

这似乎不起作用:

Object of class Cake\Database\Expression\FunctionExpression could not be converted to string

$users = $this->Users->find();
$users->select(['id', 'fname', 'lname'])
    ->where([$users->func()->concat(['fname', 'lname']).' LIKE' => $terms]);

有什么想法吗?

谢谢。

【问题讨论】:

    标签: cakephp cakephp-3.0 query-builder cakephp-3.x


    【解决方案1】:

    如果你要连接名字和姓氏,它们之间应该用空格连接。

    $users->select(['id', 'fname', 'lname'])
          ->where(function ($exp, $query) use ($terms) {
             $conc = $query->func()->concat([
                'fname' => 'identifier', ' ',
                'lname' => 'identifier'
             ]);
             return $exp->like($conc, $terms);
           });
    

    【讨论】:

    • 这行得通。谢谢。我还将第二个 like 参数更改为(以防其他人有同样的问题):like($conc, '%'.$terms.'%');
    【解决方案2】:

    你必须使用查询表达式,但这不能在分页数组中完成。

    所以按照 ndn 的建议,我会这样做

    创建自定义查找器。在您的 UsersTable 文件中

    public function findByKeyword(Query $query, array $options)
    {
        $keyword = $options['keyword'];
        $query->where(
            function ($exp, $q) use($keyword){
                $conc = $q->func()->concat([
                    'Users.fname' => 'literal', ù
                    'Users.lname' => 'literal']);
                return $exp
                    ->or_([
                        'Users.fname LIKE' => "%$keyword%",
                        'Users.lname LIKE' => "%$keyword%",
                    ])
                    ->like($conc, "%$keyword%");
                }
            );
        return $query;
    }
    

    控制器

    $this->paginate = [
            'finder' => [
                'byKeyword' => [
                    'keyword' => $this->request->data['Users']['keyword']
            ]],
            'conditions' => $limo,  // this will merge your $limo conditions                  
                                    // with the ones you set in the custom finder
            'order'= > ['Users.fname desc'],
        ];
    
    $this->set('userlist', $this->paginate($this->Users));
    

    【讨论】:

      【解决方案3】:

      我认为你必须使用 SQL 表达式。试试这样的:

      ->where(function ($exp, $q) use($terms) {
          $concat = $q->func()->concat([
              'fname' => 'identifier', 
              'lname' => 'identifier'
          ]);
          return $exp->like($concat, $terms);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-25
        • 2017-12-22
        • 1970-01-01
        • 2015-11-15
        • 1970-01-01
        相关资源
        最近更新 更多