2011-07-18 64 views
-1

我在我的數據庫中有這些表:'產品'屬於'公司','公司'有許多'company_addresses'。我在我的控制器中建立一個搜索動作,它會根據用戶輸入的公司地址返回產品。我怎麼能得到如下的東西?CakePHP 3級聯接查找方法

SELECT * 
FROM products 
LEFT JOIN companies ON products.company_id = companies.id 
LEFT JOIN company_addresses ON companies.id = company_addresses.company_id 
WHERE company_addresses.address1 LIKE '%'.$this->data['Product']['keyword'].'%' 
OR company_addresses.address2 LIKE '%'.$this->data['Product']['keyword'].'%' 

這似乎並不工作:

$results = $this->Product->find('all', array(
    'conditions' => array(
     'OR' => array(
      array('CompanyAddress.address1 LIKE' => '%'.$this->data['Product']['keyword'].'%'), 
      array('CompanyAddress.address2 LIKE' => '%'.$this->data['Product']['keyword'].'%') 
     ) 
    ), 
    'order' => array(
     'Product.id' => 'ASC' 
    ), 
    'contain' => array(
     'Company' => array(
      'CompanyAddress' => array(
       'State', 
       'City' 
      ) 
     ) 
    ) 
)); 

這也不:

$results = $this->Product->find('all', array(
    'order' => array(
     'Product.id' => 'ASC' 
    ), 
    'contain' => array(
     'Company' => array(
      'CompanyAddress' => array(
       'conditions' => array(
        'OR' => array(
         array('CompanyAddress.address1 LIKE' => '%'.$this->data['Product']['keyword'].'%'), 
         array('CompanyAddress.address2 LIKE' => '%'.$this->data['Product']['keyword'].'%') 
        ) 
       ), 
       'State', 
       'City' 
      ) 
     ) 
    ) 
)); 

回答

0

我想對你最好的是使用CakePHP的加入。

事情是這樣的:

$this->Product->find('all', array(
          'joins' => array(
           array(
            'table' => 'companies', 
            'alias' => 'Company', 
            'type' => 'left', 
            'conditions' => array(
             'Company.id = Product.company_id' 
            ), 
           ), 
           array(
            'table' => 'companies_addresses', 
            'alias' => 'CompaniesAddress', 
            'type' => 'left', 
            'conditions' => array(
             'CompaniesAdress.company_id = Company.id', 
             'OR' => array(
              'CompanyAdress.address1 LIKE' => '%' . $this->data['Product']['keyword'] . '%', 
              'CompanyAdress.address2 LIKE' => '%' . $this->data['Product']['keyword'] . '%', 
             ), 
            ), 
           ), 
          ), 
         ));