【问题标题】:CakePHP SQL-query countCakePHP SQL 查询计数
【发布时间】:2018-05-04 23:46:12
【问题描述】:

我有一个关于 CakePHP SQL 查询的问题。我需要从给出 shop_id 的数据库中获取产品,然后对产品进行计数。我只需要 Product.url 及其数量。

这将在简单的 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 获得相同的结果?

【问题讨论】:

标签: sql cakephp


【解决方案1】:

你可以试试这个:

$data = $this->Post->query(
    "SELECT COUNT(id),MONTH(created) FROM posts GROUP BY YEAR(created), MONTH(created);"
);

【讨论】:

    【解决方案2】:

    最简单的方法:

    $this->Product->query("SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC;");
    

    ...至少对我来说。

    【讨论】:

      【解决方案3】:

      试试下面的代码:

      $this->Product->virtualFields['CNT_PRODUCTS'] = 0;
      $this->Product->find('count', array('conditions' => array('Product.shop_id' => $id),
                                          'fields' => array('Product.id', 'Product.url', 'count(*) as CNT_PRODUCTS'),
                                          'order' => array('CNT_PRODUCTS' => 'DESC'),
                                          'group' => 'Product.url'));
      

      【讨论】:

      猜你喜欢
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多