2014-12-22 90 views
1

Cakephp 2.6如何在cakephp中運行子查詢

我有一個Model,Temps,它有很多票。在我希望爲每個記錄返回的Temps的索引視圖中,日期最接近當前日期的票證。

在MySQL中是可以做到的

'SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() ORDER BY expiry_date ASC LIMIT 1' 

但我不知道如何作爲一個子查詢運行此。我目前的產生我的成績查詢如下:(銘記這已被配置爲數據表)門票是用於上傳模式

public function getAjaxIndexData($data) { 
      $tokens = explode(" ", $data['searchString']); 
      $conditions = array(
       $this->alias . '.deleted' => false, 
       'OR' => array(
        'CONCAT(' . $this->alias . '.first_name," ",' . $this->alias . '.last_name) LIKE' => '%' . implode(' ', $tokens) . '%', 
       ), 
       $data['columnsFilter'] 
      ); 
      $fields = array(
       'id', 
       'full_name', 
       'pps_number', 
       'mobile', 
       'email', 
       'start_date', 
       'time_served' 
      ); 
      $order = array(
       $data['orderField'] => $data['order'] 
      ); 
      $contain = array(
       'LocalOffice.name', 
      ); 

      $options = array(
       'conditions' => $conditions, 
       'fields' => $fields, 
       'order' => $order, 
       'contain' => $contain, 
       'limit' => $data['limit'], 
       'offset' => $data['start'] 
      ); 
      $optionsNoFields = array(
       'conditions' => $conditions, 
       'contain' => $contain, 
      ); 

      $result['draw'] = $data['draw']; 
      $result['recordsTotal'] = $recordTotal = $this->find('count'); 
      $result['recordsFiltered'] = $this->find('count', $optionsNoFields); 
      $result['data'] = $this->find('all', $options); //standard search 
      $result['data'] = $this->formatTable($result['data']); 

      return json_encode($result); 
     } 

在此查詢我想添加一個字段的別名,顯示每個溫度最近的有效期限。

我該如何構造這個?

+1

看一看http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries – bish

回答

2

動態創建一個虛擬域:

$this->virtualFields['nearest'] = '(SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() AND uploads.owner_id = '.$this->alias.'.ticket_id ORDER BY expiry_date ASC LIMIT 1')'; 

然後調整自己的領域陣列

 $fields = array(
      'id', 
      'full_name', 
      'pps_number', 
      'mobile', 
      'email', 
      'start_date', 
      'time_served', 
      'nearest' 
     ); 

此外,查詢可以被改寫爲( 「TEMP」 需要被替換型號別名)

SELECT MIN(expiry_date) 
FROM uploads 
WHERE expiry_date > CURDATE() 
    AND uploads.owner_id = temp.ticket_id; 

這意味着可能更好的執行查詢將是將該子查詢從SELECT語句的列移出到JOIN。例如:

SELECT * 
FROM temp 
LEFT JOIN (SELECT MIN(expiry_date) AS expiry,owner_id 
    FROM uploads 
    WHERE expiry_date > CURDATE()) 
    GROUP BY owner_id) AS next_dates 
    ON next_dates.owner_id = temp.ticket_id; 
+0

此虛擬場方法返回相同的值每個結果都是從數據庫中選擇的。我可以通過添加如uploads.owner_id(FK)= temp.ticket_id –

+1

@ mcgowan.b - 我更改了代碼以匹配您的新信息 – AgRizzo