【发布时间】:2013-10-10 19:13:56
【问题描述】:
我使用的是 CakePHP 1.3,在将 SQL 查询转换为 CakePHP 时遇到了一些问题。查询背后的概念是检索与指定帐户关联并属于某个产品类别或指定类别的直接子级的所有产品。
这里涉及到三个表,products、product_categories 和 category_types。 product_categories 是将产品连接到 category_types 的链接表。 category_types 表是一个可以连接到自身的树结构。
如果类别的 id 为 1 且帐户的 id 为 1,则查询的 SQL 最终应如下所示:
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
)
)
));
问题是查询忽略了 account_id OR 条件,导致 SQL 如下:
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 代码以获得所需的结果?
【问题讨论】:
-
您在条件数组中有两次声明键“OR”,因此第二个将覆盖第一个。你需要做一些允许多个 or 条件的事情,也许像stackoverflow.com/questions/13890704/…
标签: cakephp