在 cakephp 3 中使用 concat 字段进行搜索

问题描述 投票:0回答:1

我需要在 CakePHP 3 中使用

$this->Paginate
进行搜索查询。以下是我正在使用的代码

$searchCondition = array(
    'OR' => array(
        'Quotes.quotenum LIKE' => "%" . $this->request->data['Quote']['keyword'] . "%",
        'Branches.name LIKE' => '%' . $this->request->data['Quote']['keyword'] . '%',
        'Contacts.fname LIKE' => '%' . $this->request->data['Quote']['keyword'] . '%',
        'Contacts.lname LIKE' => '%' . $this->request->data['Quote']['keyword'] . '%',
        'CONCAT(Contacts.fname, Contacts.lname) LIKE' => '%' . $this->request->data['Quote']['keyword'] . '%',
        'Quotes.description LIKE' => '%' . $this->request->data['Quote']['keyword'] . '%'
    )
);

$cond = array(
    'conditions' => array_merge($searchConditions, $searchCondition, $limo),
    'order'= > array('Quotes.quotenum desc'),
    'contain' => array('Branches','Contacts')
);

$this->set('articleList', $this->paginate($this->Quotes));

如您所见,我将条件数组相互合并,然后将它们发送到分页。这在 CakePHP 2.7 中运行良好。但是现在我得到了错误

Column not found: 1054 Unknown column 'contacts.lname' in 'where clause'.

lname
列肯定存在于数据库表中。我做错了什么吗?如果是这样,有人可以告诉我进行连续搜索的正确方法吗,因为我已经尝试这样做很长一段时间了。

php cakephp cakephp-3.0 query-builder
1个回答
2
投票

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

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

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

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

然后在你的控制器中

$this->paginate = [
        'finder' => [
            'byKeyword' => [
                'keyword' => $this->request->data['Quote']['keyword']
        ]],
        'conditions' => $limo,  // this will merge your $limo conditions                  
                                // with the ones you set in the custom finder
        'order'= > ['Quotes.quotenum desc'],
        'contain' => ['Branches','Contacts']
    ];

$this->set('articleList', $this->paginate($this->Quotes));
© www.soinside.com 2019 - 2024. All rights reserved.