2013-07-22 73 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查詢 –