1

数据库中的每个Order都有一个product_id. Product每个订单只有一个。

从 中ProductsController,我想显示所有产品,并在每个产品旁边显示订购了多少次。我将需要包含一个条件以排除任何具有deleted = 0

4

3 回答 3

3

我也会使用counterCache

将 order_count 字段添加到您的 Product 表并修改 Order 模型

class Order extends AppModel {
    public $belongsTo = array(
        'Product' => array(
            'counterCache' => true,
            'counterScope' => array('Product.deleted' => 0)
        )
    );
}
于 2013-01-16T08:27:19.690 回答
2

此查询应返回您需要的结果。根据需要调整条件、附加字段等。

$data = $this->Order->find('all',array( 
   'fields'=>array(
       'COUNT(Product.id)as Count',
       'Product.id','Product.name'
   ), 
   'group'=>array(
       'Product.id'
   ), 
   'contain'=>'Product' 
));
于 2013-01-16T23:32:23.597 回答
1

一个简单find('count')的就足够了(此查找操作的详细信息在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;
}

正如 Mark 所建议的那样, aGROUP BY也应该做到这一点,并通过仅使用一个 find 来简化过程。

$count = $this->Product->Order->find('count', array(
    'conditions' => array(
        'Order.product_id' => $product_id,
        'Product.deleted' => 0
    ),
    'group' => array('Order.product_id')
));
于 2013-01-15T18:28:28.277 回答