我有關於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相同的結果?
它通常是更好地利用「虛擬域」此:http://book.cakephp.org/2.0/en/models/virtual-fields.html – mark