Sql CakePHP:存在或与UNION连接

Sql CakePHP:存在或与UNION连接,sql,cakephp,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

我需要在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中进行此查询?

在产品模型中创建一个函数,并编写以下代码:

$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…

在上述查询中按产品id使用分组