我的数据库中有这些表:'产品'属于'公司','公司'有很多'company_addresses'。我正在我的控制器中构建一个搜索操作,它将根据用户输入的公司地址返回产品。我怎样才能得到像下面这样的东西?
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 :(得分: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'] . '%',
),
),
),
),
));