在cakephp中使用虚拟字段求和值

在cakephp中使用虚拟字段求和值,php,mysql,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

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

说这是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);
}

您可以通过以下方式执行相同操作:

$this->Post->virtualFields['TotalVotes'] = 0;
$query = $this->Post->query("select posts.user_id, SUM(Posts.vote_total) as TotalVotes from posts where posts.type = 'new' group by posts.user_id");
$this->set('posts', $query);
一定会帮助你达到你所要求的目标。 请询问它是否对您有效。

我收到以下错误:“未找到列:字段列表中的1054未知列'Post.total'。我假设“字段”选项不能正确识别虚拟字段……再想想,虚拟字段真的有必要吗?我不能设置field=sum(…)吗?