分组并计算 cakephp 未返回预期结果
group by and count cakephp not returning expected result
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'
));
返回第一个产品标题,总计 post(不是产品标题)和 post 个与第一个产品相关的
检查 join with 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);
根据cake doc解决了。查询应该像
$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);
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'
));
返回第一个产品标题,总计 post(不是产品标题)和 post 个与第一个产品相关的
检查 join with 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);
根据cake doc解决了。查询应该像
$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);