cakephp:我如何显示每个类别的计数?

时间:2016-02-12 08:22:19

标签: php mysql cakephp count

这是我的表格

brands_tbls

  • id 1 2 3 4
  • name Levi's Lee Woodland Spyakr

product_tbls

  • id
  • brands_tbls_id
  • product_description
  • name
  • price

我正在展示我的品牌,并尝试使用此代码进行产品计数。

PublicController.php

public function example()
{
    $this->loadModel("Brand");
    $data = $this->Brand->find('all');
    $this->set('brand', $data);
    $this->layout="display";


    $this->loadModel("Product");
    $data = $this->Product->find('count', array('conditions' =>
                                  array('brands_tbls_id' => '1')));
    $this->set('product1', $data);
    $this->layout="display";
}

下面是我的视图文件

example.ctp

<?php foreach($brand as $data) : ?>
  <?php foreach($data as $row) : ?>
   <li>
     <a href="#">
        <span class="pull-right">(<?php echo $product1;//--count   ?>)
        </span><?php echo $row["name"];//--brands   ?>
     </a>
   </li>
   <?php endforeach; ?>
<?php endforeach; ?>

通过这样做,我可以从product_tbls brands_tbls_id = 1

获取... -rw-r--r-- 3.0 unx 2939 bx 2677 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 15069 bx 3040 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 3265 bx 3003 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 3048 bx 2766 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 3453 bx 3168 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 1415 tx 534 defN 16-Jan-28 16:33 <file_name> drwxr-xr-x 3.0 unx 0 bx 0 stor 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 3302 tx 695 defN 16-Jan-28 16:33 <file_name> drwxr-xr-x 3.0 unx 0 bx 0 stor 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 130678 bx 127322 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 133540 bx 130045 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 136 tx 71 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 1416 tx 541 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 1417 tx 541 defN 16-Jan-28 16:33 <file_name> -rw-r--r-- 3.0 unx 2766 tx 652 defN 16-Jan-28 16:33 <file_name> 5551 files, 3854751563 bytes uncompressed, 3793408959 bytes compressed: 1.6% 的产品数量

因此它将显示所有品牌的相同产品数量。我可以获得所有品牌的产品数量吗?

2 个答案:

答案 0 :(得分:0)

您在$ brand中的记录是您拥有的品牌数量。

<?php echo count($brand); ?>

如果你想对品牌进行计数,你可以在Cakephp 2.x

中这样做
$data = $this->Brand->find('count');

有点不清楚你想要实现的目标。

答案 1 :(得分:0)

您希望实现的目标是按品牌分组您的产品

$data = $this->Product->find(
   'all', 
    array(
        'fields' => array('COUNT(*)'),
        'group' => 'brands_tbls_id',
        'contain' => array('Brand')
   )
);

因此您可以循环浏览$data

相关问题