【发布时间】:2014-11-24 02:07:29
【问题描述】:
我想统计某个Script 中来自ScripRating 的赞成票和反对票的数量。
Script.php:
public function ratings()
{
return $this->hasMany('ScriptRating');
}
ScriptRating.php:
public function script()
{
return $this->belongsTo('Script');
}
script_rating 数据库表:
id (primary, increments)
script_id(integer)
rating(integer) <-- Can be either 1 (upvote) or -1 (downvote)
检索脚本并显示评分:
$script = Script::where('title', '=', $title)->get();
{{ $script->ratings }}
这很好用,它返回一个数组:[{"id":1,"script_id":1,"rating":1}]。但在这一点上,我被困住了。我如何计算某个脚本的赞成票和反对票总数?
我还有一个小问题,让我感到困惑。这与上面的代码相同:
$script = Script::where('title', '=', $title)->with('ratings')->get();
{{ $script->ratings }}
这两种方法有什么区别,我应该使用哪一种?
提前致谢!
编辑
我做了三个范围:
public function scopeTotalRating($query, $scriptId) {
return $query->where('script_id', $scriptId)->get()->sum('rating');
}
public function scopeThumbsUp($query, $scriptId) {
return $query->where('script_id', $scriptId)->having('rating', '=', 1)->get()->sum('rating');
}
public function scopeThumbsDown($query, $scriptId) {
return $query->where('script_id', $scriptId)->having('rating', '=', -1)->get()->sum('rating');
}
并显示如下:
{{ ScriptRating::thumbsUp($script->id) }}
【问题讨论】:
标签: laravel model count eloquent relationship