0

任务

我正在尝试根据相关模型中的条件返回一组数据。

问题

目前我能得到的最接近的是使用 Containable 返回所有匹配的模型数据,但仅在匹配包含条件时才返回子数据。这并不理想,因为我的数据仍然包含主要模型数据,而不是被删除。

我正在使用 HABTM 关系,例如Product和之间的关系,Category并且我想查找特定类别中的所有产品。

最初的想法

基本方法是使用可包含的。

$this->Product->find('all', array(
    'contain' => array(
        'Category' => array(
            'conditions' => array(
                'Category.id' => $categoryId
            )
        )
    )
));

尽管这将返回所有产品,并且如果 Category 维度与包含条件不匹配,则只需删除它。

迄今为止最近的

$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

这个查询是正确的,除了连接条件被引用 ' 而不是 `,这会中断查询。

手动查询

SELECT * 
FROM products
JOIN categories_products ON categories_products.product_id = products.id
JOIN categories ON categories.id = categories_products.category_id
WHERE categories.id = 12
4

1 回答 1

1

问题在于我定义连接条件的方式。它不是一个关联数组,而是一个字符串。

        'conditions' => array(
            'CategoriesProduct.product_id' => 'Product.id'
        )

更改为

        'conditions' => array(
            'CategoriesProduct.product_id = Product.id'
        )
于 2013-02-20T11:09:08.770 回答