我想要計算ScripRating
對於某個Script
的upvotes和downvotes的數量。相關模型的Laravel計數列
的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) }}
感謝您的評論。我試過上面的代碼,但我無法弄清楚如何使用它。我如何檢索向下/向上投票?另外,你知道我的第二個問題的答案嗎? – JasonK 2014-09-29 17:51:30
謝謝!你可以在我的第一篇文章中看到我做了什麼。我現在遇到的唯一問題是這個錯誤:'類Illuminate \ Database \ Eloquent \ Builder的對象無法轉換爲字符串'這在腳本沒有任何評級時發生。你知道如何解決這個問題嗎? – JasonK 2014-09-29 19:15:51