2013-07-22 70 views
0

我有关于CakePHP SQL查询的问题。我需要从提供shop_id的数据库中获取产品,然后对产品进行计数。我需要的只是Product.url和它的数量。CakePHP SQL查询计数

这将这样的伎俩在普通的SQL:

SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC; 

这一个我曾经获得的所有产品有关的商店:

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

即正常工作,但我需要转换的是SQL - 查询CakePHP。

我想是这样的:

$this->Product->find('count', array('conditions' => array('Product.shop_id'=>$id), 
             'fields'=>array('Product.url','Product.id'), 
             'order'=>'count DESC', 
             'group'=>'Product.url')); 

只返回一个int。但是如果我在mysql服务器上运行上面提到的SLQ查询,我会得到两列:url和count。如何获得与CakePHP相同的结果?

+0

它通常是更好地利用“虚拟域”此:http://book.cakephp.org/2.0/en/models/virtual-fields.html – mark

回答

1

要做到这一点,最简单的方法:

$this->Product->query("SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC;"); 

...至少对我来说。

+0

我看看你在那里做了什么.... http://cmi.memecdn.com/35/541035.jpg .... –

1

试试下面的代码:

$this->Product->virtualFields['CNT_PRODUCTS'] = 0; 
$this->Product->find('count', array('conditions' => array('Product.shop_id' => $id), 
            'fields' => array('Product.id', 'Product.url', 'count(*) as CNT_PRODUCTS'), 
            'order' => array('CNT_PRODUCTS' => 'DESC'), 
            'group' => 'Product.url')); 
+0

看到这个链接:http://book.cakephp.org/2.0/en/models/virtual -fields.html#虚拟领域,在-SQL查询 –