group by和count cakephp没有返回预期的结果

时间:2016-03-29 05:13:35

标签: cakephp cakephp-2.0

Sql查询工作正常,但在cakephp中没有返回预期的输出。

SELECT products.product_id, products.product_title, COUNT(posts.post_id)
AS total_post
FROM products
LEFT JOIN posts ON posts.product_id = products.product_id
GROUP BY products.product_id

cakephp查询构建器

    $products = $this->Product->find('all',array(
        'Product.is_active' => 1,
        'fields'=>array(
            'Product.product_id, Product.product_title,COUNT(Post.post_id) as total_post'
        ),
        'joins'=>array('LEFT JOIN posts as Post ON Post.product_id = product.product_id'),
        'GROUP'=>'Product.product_title'
    ));

返回第一个产品标题,总帖子(不是产品标题明智)和与第一个产品相关的帖子

2 个答案:

答案 0 :(得分:0)

查看与group by联接的示例,看看你出错了什么

 $options = array(
                'conditions' => $conditions,
                'fields'=>array('Category.*','COUNT(`Entity`.`id`) as `entity_count`'),
                'joins' => array('LEFT JOIN `entities` AS Entity ON `Entity`.`category_id` = `Category`.`id`'),
                'group' => '`Category`.`id`',
                'contain' => array('Domain' => array('fields' => array('title')))
            );

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

答案 1 :(得分:0)

根据蛋糕医生解决了它。查询应该像

$options['joins'] = array(
        array('table' => 'posts',
            'alias' => 'Post',
            'type' => 'LEFT',
            'conditions' => array(
                'Post.product_id = Product.product_id',
            )
        )
    );
    $options['conditions'] = array(
        'Product.is_active' => 1
    );
    $options['fields'] = array(
        'Product.product_id, Product.product_title,COUNT(Post.post_id) as total_post'
    );
    $options['group'] = array(
        'Product.product_title' 
    );
    $options['recursive'] = 0;
    $products = $this->Product->find('all', $options);