【问题标题】:Getting the average of a database column from matching records in CakePHP 2.9从 CakePHP 2.9 中的匹配记录中获取数据库列的平均值
【发布时间】:2018-08-28 16:50:29
【问题描述】:

有没有办法(完全自定义 SQL 之外)从匹配 CakePHP 2.9 中某些条件的记录中找到表列的平均值?

例如,我可以通过调用 Field 模型轻松找到字段列表:

$fields = $this->Field->find('all', array(
    'conditions' => array(
        'User.username' => 'John Doe',
        'Report.created' => '2018-01-01'
    )
);

但是,对于所有匹配的记录,我真正想要得到的是Field.value平均值

我通常会做一个原始的 SQL 查询;

$average = $this->Field->query('
    select avg(f.value) as average from fields f 
      left join users u on (f.user_id = u.id) 
      left join reports r on (f.report_id = r.id) 
      where u.username = "John Doe" and r.created = "2018-01-01"
');

但是,我不一定知道条件字段是什么,我想使用 CakePHP ORM 的强大功能来构建查询。

有没有办法从Model::find 计算这个平均值?

【问题讨论】:

标签: mysql cakephp


【解决方案1】:

假设您已遵循 Cakephp 约定。您可以按如下方式对字段进行平均。

$average = $this->Field->find('all', array(
'fields' => array('AVG(Field.value) as average'),
'conditions' => array('User.username' => 'John Doe', 'Report.created' => '2018-01-01'),
'contain' => array('User', 'Report')
));

希望你能明白。

【讨论】:

  • 这行得通! @burzum 建议的问题是另一个问题是关于获取每条记录的平均值,但我需要获取 all 记录的平均值并使用 Cake ORM 的强大功能来选择哪些字段得到了平均。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多