Verwenden von virtuellen Feldern zum Summieren von Werten in cakephp
Ich versuche, die Summe der Stimmen für einen bestimmten Benutzer zu ermitteln.
Angenommen, dies ist die Post-Tabelle
id | body | user_id | vote_total | type
1 test 1 4 new
2 test2 1 3 new
3 test3 2 2 new
Ich versuche die folgende Ausgabe zu bekommen
user_id | vote_total
1 7
2 2
Hier ist meine Funktion 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);
}
Diese Abfrage funktioniert (ich habe es mit phpmyadmin versucht), aber ich kann nicht herausfinden, wie ich auf das resultierende Array zugreifen soll
edit Ich habe es mit der folgenden Abfrage zum Laufen gebracht
$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);
Wenn ich print_r eingebe, ist dies das Array
Array ( [posts] => Array ( [user_id] => 7 ) [0] => Array ( [total] => 6 ) ) 1