使用虚拟字段对cakephp中的值求和 [英] using virtual fields to sum values in cakephp
本文介绍了使用虚拟字段对cakephp中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图获得给定用户的投票总额。
说这是帖子表
id |身体| user_id | vote_total |类型
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);
}
I'm trying to get the sum of votes for a given user.
Say this is posts table
id | body | user_id | vote_total | type
1 test 1 4 new
2 test2 1 3 new
3 test3 2 2 new
I'm trying to get the following output
user_id | vote_total
1 7
2 2
Here's my function in 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);
}
This query works (I tried with phpmyadmin) but I can't figure out how to access the resulting array
edit I got it to work using the following query
$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);
when I type print_r this is the array
Array ( [posts] => Array ( [user_id] => 7 ) [0] => Array ( [total] => 6 ) ) 1
解决方案
I think your array is messed up. also, where do you set the virtual fields for the model? last but not least: why a query inside a query?
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);
}
这篇关于使用虚拟字段对cakephp中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文