2

我正在使用 cakephp 2.1,我想获得特定电影的平均电影收视率。其中“Movie”是一个模型,它包含“Language”和“CriticReview”作为模型。数组结构如下。

    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'
                    )
    )
));

所以我必须平均评论评论。请帮我找出解决方案。这项工作将是可观的。

4

1 回答 1

2

我不知道您的查询现在如何,但您可以尝试添加此字段:

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

返回的数组现在将在每部电影中包含一个子数组,其键0如下

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

我个人更喜欢保存计算数据而不是即时计算。也许您想阅读这个问题:MySQL - 即时计算字段与存储计算数据

于 2012-10-25T21:00:00.037 回答