2014-09-22 84 views
0

我正在構建一個使用CakePHP的應用程序,並且我在使用一系列連接檢索數據時遇到問題。在下面的簡化示例中,與別名「交付」的聯接可能有更多的記錄,我想在表中的特定字段中將帶有最大值的記錄帶回。CakePHP從多個表中檢索具有選擇條件的數據

SELECT 
    jobs.JOB_ID, 
    jobs.CUSTOMER, 
    functional.JOB_LINE_ORDER, 
    functional.CNOR_CNEE_NAME, 
    functional.TOWN_NAME 
FROM jobs JOIN functional ON 
      jobs.JOB_ID = 'M201409180267' 
     AND 
      functional.JOB = jobs.JOB_ID 
     AND 
      functional.TYPE_STAGE = 0 
     AND 
      functional.JOB_LINE_ORDER = 
       (SELECT MAX(JOB_LINE_ORDER) FROM functional 
       WHERE functional.JOB = 'M201409180267' AND functional.TYPE_STAGE = 0) 

我已經嘗試使用下面的條件數組:

'conditions' => array('AND ' => 
          array('Invoice.job_id = Delivery.JOB', 
            'Delivery.TYPE_STAGE = 1' 
            'Delivery.JOB_LINE_ORDER = MAXIMUM(Delivery.JOB_LINE_ORDER)') 
          ) 

這並帶回的結果,但不是

$inv_conditions = array( 'Invoice.invoice_date >=' => $DateFormatter->dateForDB($dateFrom), 
       'Invoice.invoice_date <=' => $DateFormatter->dateForDB($dateTo), 
       'Invoice.id >' => 385380);  

$join = array(array(
       'table' => 'jobs', 
       'alias' => 'Jobs', 
       'type' => 'LEFT', 
       'conditions' => array('Invoice.job_id = Jobs.JOB_ID') 
      ),  
      array(
       'table' => 'functional', 
       'alias' => 'Delivery', 
       'type' => 'LEFT' 
       'conditions'=> array('AND ' => array('Invoice.job_id = Delivery.JOB', 
                'Delivery.TYPE_STAGE = 1') 
          ) 
        ) 

     );  

$invoices = $this->Invoice->find("all", array(
       "fields" => array(
          'Invoice.id', 
          'Invoice.job_id', 
          'Invoice.invoice_no', 
          'Invoice.consolidated_type', 
          'Invoice.customer_id_tbc', 
          'Invoice.invoice_date', 
          'Invoice.invoice_reference', 
          'Invoice.invoice_req', 
          'Jobs.PAYMENT_TYPE', 
          'Jobs.CUSTOMER', 
          'Jobs.MOST_RELEVANT_LINE', 
          'Delivery.DEPARTURE_DATE', 
          'Delivery.CNOR_CNEE_NAME', 
          'Delivery.TOWN_NAME', 
          ), 
       "conditions" => $inv_conditions, 
       "joins"  => $join 
       ) 
      ); 

} 

我可以如下用SQL這樣做沒有問題正確的和由Cake生成的結果SQL在where子句中有select。有沒有辦法做到這一點時檢索數據蛋糕中創建的SQL語句將在where子句中有選擇。

任何建議將不勝感激。 謝謝 基礎

回答

0

您需要使用子查詢來生成where子句中的select。您可以在您的模型中創建一個方法,然後從您的控制器調用它。

$subQuery = $db->buildStatement(
      array(
       'fields'  => array(''), 
       'table'  => $db->fullTableName($this), 
       'alias'  => 'aliasName', 
       'limit'  => null, 
       'offset'  => null, 
       'joins'  => array(), 
       'conditions' => $conditionsArray, 
       'order'  => null, 
       'group'  => null 
      ), 
      $this 
     ); 
     $subQuery = ' <<YOUR MAIN QUERY CONDITION (' . $subQuery . ') >>'; 
     $subQueryExpression = $db->expression($subQuery); 

     $conditions[] = $subQueryExpression; 
     return $this->Model->find('list', compact('conditions')); 
相關問題