CakePHP 2.1 Avg function for query

拜拜、爱过 提交于 2019-12-11 10:28:11

问题


I am using cakephp 2.1 and I wanna get average of movie ratings for perticular movie. Where 'Movie' is a model and it contains 'Language' and 'CriticReview' as models. The array structure is as follows.

    array(
(int) 0 => array(
    'Movie' => array(
        'id' => '4',
        'name' => 'Maattrraan',
        'cover_image' => '/movies/4d0d1c41d956a2cb2ab93603d1fdf70c.jpg',
        'release' => '2012-10-12',
        'runtime' => '',
        'budget' => '65 crore',
        'box_office' => '',
        'language_id' => '2',
        'industry_id' => '3'
    ),
    'Language' => array(
        'id' => '2',
        'name' => 'tamil'
    ),
    'CriticReview' => array(
        (int) 0 => array(
            'rating' => '4',
            'movie_id' => '4'
        ),
                    (int) 1 => array(
                            'rating' => '3',
                            'movie_id' => '4'
                    )
    )
),
(int) 1 => array(
    'Movie' => array(
        'id' => '1',
        'name' => 'Romeo',
        'cover_image' => '/movies/32aa2788fa5e1584d4c627c56214574e.jpg',
        'release' => '2012-07-06',
        'runtime' => '',
        'budget' => '',
        'box_office' => '',
        'language_id' => '1',
        'industry_id' => '1'
    ),
    'Language' => array(
        'id' => '1',
        'name' => 'kannada'
    ),
    'CriticReview' => array(
        (int) 0 => array(
            'rating' => '6',
            'movie_id' => '1'
        ),
                    (int) 1 => array(
                            'rating' => '3',
                            'movie_id' => '1'
                    )
    )
));

So I have to avg of critic review. Please help me to find out the solution. The work will be appreciable.


回答1:


I don't know how your query looks like now, but you can try to add this field:

$this->Movie->find("all", array(
    "fields"     => array("AVG(CriticReview.rating) AS AverageRating"),
    "conditions" => ...
));

The array returned will now contain a sub array within each movie with a key 0 like this

[0] => Array
    (
        [AverageRating] => AVG_CALCULATED_BY_MYSQL
    )

I personally prefer to save calculated data instead of calculate it on fly. Maybe you'd like to read this question: MySQL - Calculating fields on the fly vs storing calculated data



来源:https://stackoverflow.com/questions/13069353/cakephp-2-1-avg-function-for-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!