php - 使用虚拟字段对 cakephp 中的值求和

标签 php mysql cakephp

我正在尝试获取给定用户的投票总和。

假设这是 posts 表

id | body  | user_id | vote_total | type
1    test     1          4          new
2    test2    1          3          new
3    test3    2          2          new

我正在尝试获得以下输出

user_id  | vote_total
 1          7
 2          2

这是我在 PostsController 中的函数

 public function topvotes(){ 
    $virtualFields = array('total' => 'SUM(Post.vote_total)');
    $total = $this->Post->find('all', array(
                            array('fields' => array('total'), 
                            'recursive' => 1,
                            'group' => array('Post.user_id'),
                            'conditions'=>array('Post.type' => 'new' ))));

    $post = $this->Post->find('all', $total);
    $this->set('posts', $post);
}

此查询有效(我尝试使用 phpmyadmin)但我不知道如何访问结果数组

编辑我使用以下查询让它工作

$query = $this->Post->query("select posts.user_id, SUM(Posts.vote_total) from posts where posts.type = 'new' group by posts.user_id");
    $this->set('posts', $query);

当我输入 print_r 时,这是数组

Array ( [posts] => Array ( [user_id] => 7 ) [0] => Array ( [total] => 6 ) ) 1

最佳答案

我认为你的数组搞砸了。另外,你在哪里设置模型的虚拟字段? 最后但同样重要的是:为什么查询中包含查询?

public function topvotes() { 
    $this->Post->virtualFields = array('total' => 'SUM(Post.vote_total)');
    $posts = $this->Post->find('all', array(
                            'fields' => array('total'),
                            'recursive' => 1,
                            'group' => array('Post.user_id'),
                            'conditions'=>array('Post.type' => 'new')
    ));
    $this->set('posts', $posts);
}

关于php - 使用虚拟字段对 cakephp 中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11855948/

相关文章:

我网站上的 PHP 页面显示为空白

javascript - 如何对另一个文件进行 POST 并将该文件加载到主文件中?

php - 当订单 ID 不可用时,在 WooCommerce 电子邮件中获取订单元数据

php - 如何在 SQL 中插入保留字为 "from"的记录?

mysql - 如何记录查询及其在数据库上运行的每个查询的执行时间?

php - 在 cakephp 中使用模型类名 "Class"

php - Mysql 特殊字符自然排序

php - 更新或检索数据库中行的最佳方法是什么?

php - 我应该如何使用 CakePHP 3.0 中的 PHPUnit 测试此行为?

php - 如何计算 CakePHP 3.x 中 page() 使用的 OFFSET 值?