2016-02-15 69 views
2

我需要在CakePHP中使用三一$this->Paginate搜索查詢以下是我使用搜索與CakePHP中CONCAT領域3

$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列肯定會退出數據庫表。有什麼我做錯了嗎?如果是這樣,有人可以告訴我做連續搜索的正確方法,因爲我一直在嘗試做相當一段時間。

+0

你沒有使用'$ cond'變量在任何地方你的代碼示例。此外,爲什麼別名在它的小寫錯誤消息中有所不同,在您的代碼片段中以大寫字母開頭? – ndm

+0

@ndm它似乎是降低別名的蛋糕。我測試了一個類似的代碼,並得到相同的錯誤。我試過的代碼只是'$ table-> find() - > where(['CONCAT(Users.name,Users.family_name)LIKE'=>'%test%']);' – arilia

+0

@arilia啊,我忽略了第二個'lname'引用...你需要使用查詢表達式。 – ndm

回答

2

Yu必須使用查詢表達式,但這不能在分頁數組中完成。

所以繼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));