微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

说这是职位表

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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐