0
任務
我試圖根據相關模型中的條件返回一組數據。如何通過篩選子模型數據來移除父模型數據?
問題
目前最接近我可以使用中可容納返回所有匹配模型的數據,但只有孩子返回的數據,如果它匹配包含條件得到。這並不理想,因爲我的數據仍然包含主要模型數據,而不是被刪除。
我使用的是HABTM關係,例如Product
和Category
,我想查找特定類別中的所有產品。
初始創意
基本的方法是使用可容納的。
$this->Product->find('all', array(
'contain' => array(
'Category' => array(
'conditions' => array(
'Category.id' => $categoryId
)
)
)
));
雖然這將返回所有產品,並且只是刪除類別維度,如果它不符合包含條件。
最近到目前爲止
$this->Product->find('all', array(
'contain' => false,
'joins' => array(
array(
'table' => 'categories_products',
'alias' => 'CategoriesProduct',
'type' => 'LEFT',
'conditions' => array(
'CategoriesProduct.product_id' => 'Product.id'
)
),
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'LEFT',
'conditions' => array(
'Category.id' => 'CategoriesProduct.category_id'
)
)
),
'conditions' => array(
'Product.status_id' => 1,
'Category.id' => $categoryId
),
));
產生下面的查詢,
SELECT `Product`.`id`, `Product`.`name`, `Product`.`intro`, `Product`.`content`, `Product`.`price`, `Product`.`image`, `Product`.`image_dir`, `Product`.`icon`, `Product`.`icon_dir`, `Product`.`created`, `Product`.`modified`, `Product`.`status_id`
FROM `skyapps`.`products` AS `Product`
LEFT JOIN `skyapps`.`categories_products` AS `CategoriesProduct` ON (`CategoriesProduct`.`product_id` = 'Product.id')
LEFT JOIN `skyapps`.`categories` AS `Category` ON (`Category`.`id` = 'CategoriesProduct.category_id')
WHERE `Product`.`status_id` = 1
AND `Category`.`id` = 12
該查詢是正確的,但連接條件被引述'而不是',它打破了查詢。