如何使用Cakephp中的count,sum和group从数据库中获取数据?

时间:2013-12-01 02:55:06

标签: mysql cakephp

我有3张桌子:产品,折扣和订单。 我试图通过使用此查询来获取数据:

SELECT discounts.product_id, products.product_name,
    sum(products.product_price - discounts.product_discount) as total_Amount,
    count(orders.order_id) as total_Number
    FROM products 
    inner join discounts on products.product_id = discounts.product_id
    inner join orders on discounts.discount_id = orders.discount_id
    group by discounts.product_id,products.product_name

这就是我在Orderscontroller中所做的:

$this->Order->recursive=2;
    $hotest_products = $this->Order->find('all',
        array( 'limit'=>20,
       'fields'=>array('Discount.product_id', 'Product.product_name',
                       'SUM(Discount.product_discount) AS total_Amount',
                       'COUNT(Order.order_id) AS total_Number'
                       ), 
       'group'=>array('Discount.product_id','Product.product_name'), 
       'order'=>array('Discount.product_id ASC')));

    $this->set('products',$hotest_products);

并在视野中:

<?php foreach ($products as $product): ?>

        <tr>    
            <td><?php echo $product ['Discount']['product_id']; ?></td>
            <td><?php echo $this->Html->link($product['Product']['product_name'], array('controller'=>'products', 'action' => 'view', $product['Discount']['product_id'])); ?></td>
            <td><?php echo $product ['Product']['total_Amount']; ?></td>
            <td><?php echo $product ['Product']['total_Number']; ?></td>
            </td>
        </tr>

        <?php endforeach; ?>

但是,我收到了一个错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Product.product_name' in 'field list'

另一个问题是,在视图中,我不知道如何获取total_Number和total_Amount,因为我不知道它们属于哪个模型。

编辑:我发现上面的代码没有加入产品表,结果是:

SELECT `Discount`.`product_id`, `Product`.`product_name`,
SUM(`Discount`.`product_discount`) AS total_Amount,
COUNT(`Order`.`order_id`) AS total_Number 
FROM `project`.`orders` AS `Order`
LEFT JOIN `project`.`users` AS `User` 
ON (`Order`.`user_id` = `User`.`user_id`) 
LEFT JOIN `project`.`discounts` AS `Discount` 
ON (`Order`.`discount_id` = `Discount`.`discount_id`) 
WHERE 1 = 1 GROUP BY `Discount`.`product_id`, `Product`.`product_name` 
ORDER BY `Discount`.`product_id` ASC LIMIT 20

但是为什么我设置recursive = 2时它不包括产品表? 3个talbes之间的联系是: 产品&gt;折扣&gt;命令。 (&gt;意味着很多)。

请帮帮我。提前致谢。

1 个答案:

答案 0 :(得分:1)

将Product.product_name更改为Products.product_name,以便从此

'fields'=>array('Discount.product_id', 'Product.product_name',
                       'SUM(Discount.product_discount) AS total_Amount',
                       'COUNT(Order.order_id) AS total_Number'
                       ), 

'fields'=>array('Discount.product_id', 'Product.product_name',
                'SUM(Discount.product_discount) AS total_Amount',
                 'COUNT(Order.order_id) AS total_Number'),