我正在使用CakePHP 1.3,並且在將SQL查詢轉換爲CakePHP時遇到了一些麻煩。查詢背後的概念是檢索與指定帳戶相關聯並屬於某個產品類別或指定類別的直接子女的所有產品。CakePHP找到所有被忽略的條件
這裏涉及三個表格,產品,product_categories和category_types。 product_categories是將產品連接到category_types的鏈接表。 category_types表是可以連接到自身的樹結構。
的查詢應該結束了尋找這樣的事情,如果類別的ID爲1,帳戶的ID的SQL爲1:
SELECT Product.id, Product.name, Product.account_id
FROM products AS Product
INNER JOIN product_categories AS pc ON (Product.id = pc.product_id)
INNER JOIN category_types AS ct ON (ct.id = pc.category_type_id)
WHERE (
((Product.account_id IS NULL) OR (Product.account_id = '1'))
AND ((ct.id = '1') OR (ct.parent_id = '1'))
)
這裏是我使用的嘗試做這樣的代碼,它位於一個函數在我的模型:
$this->find('all', array(
'joins' => array(
array(
'table' => 'product_categories',
'alias' => 'pc',
'type' => 'INNER',
'conditions' => array(
'Product.id = pc.product_id'
)
),
// get category type
array(
'table' => 'category_types',
'alias' => 'ct',
'type' => 'INNER',
'conditions' => array(
'pc.category_type_id = ct.id'
)
)
)
, 'conditions'=> array(
'OR' => array(
'Product.account_id IS NULL'
, 'Product.account_id' => $account_id
)
, 'OR' => array(
'ct.id' => $categoryTypeId
, 'ct.parent_id' => $categoryTypeId
)
)
));
的問題是查詢忽略導致SQL這樣的ACCOUNT_ID OR條件:
SELECT Product.id, Product.name, Product.account_id
FROM products AS Product
INNER JOIN product_categories AS pc ON (Product.id = pc.product_id)
INNER JOIN category_types AS ct ON (ct.id = pc.category_type_id)
WHERE ((ct.id = '1') OR (ct.parent_id = '1'))
如何更改我的php代碼以獲得所需的結果?
您的條件陣列,宣佈鍵「或」兩次,所以第二一個是覆蓋第一個。你需要做一些事情,一次允許多個或條件,可能類似於http://stackoverflow.com/questions/13890704/cakephp-complex-query-multiple-or-condition – Kai