Laravel 4 - 从模型内部返回平均分数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19262968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:32:15  来源:igfitidea点击:

Laravel 4 - Return average score from within model?

phpsqllaravellaravel-4

提问by Scully

I'd like to return the average score for game reviews in my database. I am building my site with Laravel 4.

我想在我的数据库中返回游戏评论的平均分数。我正在使用 Laravel 4 构建我的网站。

TABLE STRUCTURE:

表结构:

GAMES (id, title, etc)
REVIEWS (game_id, user_id, score, etc)

CONTROLLER:

控制器:

public function singleGame($id)
{
    $game = Game::find($id);

    if ($game)
    {
        return View::make('game')->with('game', $game);
    }
    else
    {
        return Redirect::to('/');
    }
}

My thought is to hopefully return the average score for a game through $game->average in my view, but I've been unable to produce the desired result through fiddling with my Game model.

在我看来,我的想法是希望通过 $game->average 返回游戏的平均分数,但我一直无法通过摆弄我的游戏模型来产生所需的结果。

GAME MODEL:

游戏模型:

public function scores()
{
    return $this->hasMany('Review')->avg('score');
}

I've tried a number of methods available to the query builder, but I'm still learning the ropes when it comes to Laravel/PHP, so I'm kinda stuck. Perhaps I should be approaching the problem differently?

我已经尝试了多种查询构建器可用的方法,但我仍在学习 Laravel/PHP 的诀窍,所以我有点卡住了。也许我应该以不同的方式解决问题?

Thanks.

谢谢。

回答by Matteus Hemstr?m

Here are two alternatives for you:

这里有两种选择:

Readability (two queries)

可读性(两个查询)

$game = Game::find(1);
$game->average = $game->reviews()->avg('score');

Note that this assumes that you have got a reviews function for your relationship in your game model.

请注意,这假设您在游戏模型中为您的关系提供了评论功能。

public function reviews()
{
    return $this->belongsTo('Game');
}

This alternative is using the avg aggregatefunction. The aggregate functions provided by the QueryBuilderreturns only the aggregate scalar.

这种替代方法是使用avg 聚合函数。QueryBuilder提供的聚合函数仅返回聚合标量。

Performance (one query)

性能(一个查询)

If you really want to do this in one query. Here is one alternative:

如果你真的想在一个查询中做到这一点。这是一种替代方法:

$game = Game::select('games.*', DB::raw('avg(reviews.score) AS average'))
    ->join('reviews', 'reviews.game_id', '=', 'game.id')
    ->groupBy('reviews.game_id')
    ->where('game.id', '=', 1)
    ->first();