我正在尝试获得给定用户的总票数。
说这是帖子表
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
答案 0 :(得分:4)
我认为你的阵列搞砸了。另外,你在哪里设置模型的虚拟字段? 最后但并非最不重要的:为什么在查询中查询?
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);
}
答案 1 :(得分:-1)
您可以通过以下方式执行相同操作:
$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);
This documentation page肯定会帮助您达到所需要的效果。 请问它是否对你不起作用。