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