CakePHP:与UNION共存或加入

时间:2013-12-19 08:20:28

标签: sql cakephp

我需要在CakePHP中执行下一个SQL查询

SELECT * FROM products Product
WHERE EXISTS(SELECT * FROM `products_likes` ProductsLike WHERE ProductsLike.product_id = Product.id AND ProductsLike.user_id = 9 )
OR 
EXISTS(SELECT * FROM `orders` Orders WHERE Orders .product_id = Product.id AND Orders .user_id = 9 )

或其他实施方式

SELECT Product.* FROM products Product
JOIN `products_likes` ProductsLike ON ProductsLike.product_id = Product.id
WHERE ProductsLike.user_id = 9

UNION

SELECT Product.* FROM products Product
JOIN `orders` Orders ON Orders .product_id = Product.id 
WHERE Orders.user_id = 9

如何在CakePHP中进行此查询?

1 个答案:

答案 0 :(得分:2)

在Product model中创建一个函数并写下代码:

$options = array(
        'conditions' => array(‘ProductsLike.user_id’=>9),
        'joins' => array(
            array(
                'alias' => 'ProductLike',  
                'table' => ‘products_likes’,
                'type' => 'LEFT',
                'conditions' => array(
                    'ProductLike.product_id = Product.id',
                ),
            ),
            array(
                'alias' => 'Order',  
                'table' => ‘orders',
                'type' => 'LEFT',
                'conditions' => array(
                    'Order.product_id = Product.id',
                ),
            )
        ),
        'fields' => array(“Product.*”),
        'group' => array('Product.id')
    );

 $returnData = $this->find('all',$options);

这会给你想要的结果!

... Iinjoy