数据库中的每个Order
都有一个product_id
。每个订单只有一个Product
。
从ProductsController
开始,我希望显示所有产品,并在每个产品旁边显示已订购的次数。我需要包含一个条件,以排除任何包含deleted = 0
答案 0 :(得分:3)
我也会使用counterCache
将order_count字段添加到Product表并按原样修改订单模型
class Order extends AppModel {
public $belongsTo = array(
'Product' => array(
'counterCache' => true,
'counterScope' => array('Product.deleted' => 0)
)
);
}
答案 1 :(得分:2)
此查询应返回您需要的结果。根据需要调整条件,附加字段等。
$data = $this->Order->find('all',array(
'fields'=>array(
'COUNT(Product.id)as Count',
'Product.id','Product.name'
),
'group'=>array(
'Product.id'
),
'contain'=>'Product'
));
答案 2 :(得分:1)
一个简单的find('count')
就足够了(此查找操作的详细信息在the Cookbook中):
// Get a list of all the active products
$products = $this->Product->find('list', array(
'conditions' => array('Product.deleted' => 0)
));
// Loop over the products
foreach($products as $product_id => $product) {
$count = $this->Product->Order->find('count', array(
'conditions' => array('Order.product_id' => $product_id)
));
echo "There were " . $count . " orders for " . $product;
}
正如马克所建议的那样,GROUP BY
也应该通过一次查找来完成这一过程并简化过程。
$count = $this->Product->Order->find('count', array(
'conditions' => array(
'Order.product_id' => $product_id,
'Product.deleted' => 0
),
'group' => array('Order.product_id')
));