【问题标题】:Cakephp 2.4.5 - Using Count with Sum in queryCakephp 2.4.5 - 在查询中使用 Count 和 Sum
【发布时间】:2014-04-23 15:51:01
【问题描述】:

我还没有真正看到任何在查询结果中获取 Count 值作为字段的 cakephp 示例。 这就是我所做的

    $searchfilter = array(
                        'Booking.bookingdate >=' => $date_period_current_start,
                        'Booking.bookingdate <=' => $date_period_current_end,
                        'Booking.merchant_id =' => $this->Session->read('Auth.ActiveMerchant')
                    );
    $fields       = array(
                    'COUNT(*) as reccount',
                    'SUM(Booking.pax) as totalpax',
                    );


    $bookings_period_current = $this->Booking->find('all', array('conditions' => $searchfilter, 'fields' => $fields)

    var_dump($bookings_period_current);

现在这似乎工作正常,我的 var_dump 产生:

array (size=1)
  0 => 
    array (size=1)
      0 => 
        array (size=2)
          'reccount' => string '7' (length=1)
          'totalpax' => string '28' (length=2)

我想我的问题是:

1) 这是用 cakephp 计数的正确方法吗?注意我没有使用正常的 find('Count',...) 方法

2) 在我的 $fields 变量中,我将 COUNT(*) 指定为记录...这是非常低效的吗? Bookings 表还有其他几个字段,但我真正想要的是记录总数和 Booking.pax 的总和。

干杯 凯文

【问题讨论】:

  • 据我所知,是的,这是正确的方法...。格式可能看起来很奇怪,但您可以在模型上使用 afterFind() 重新格式化您的结果...

标签: php cakephp count


【解决方案1】:

COUNT(*) 的正确方法是find('count'),但是如果您想在同一个查询中获取更多字段,您的解决方案是可以的。

你也可以使用:

a)Virtual fields

$this->Booking->virtualFields = array(
  'reccount' => 'COUNT(*)',
  'totalpax' => 'SUM(Booking.pax)'
); // or put it in Booking model
$this->Booking->find('all', array('fields' => array('reccount', 'totalpax')));

b)$this-&gt;Booking-&gt;query();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多