Laravel Model 必须返回一个关系实例

Fel*_*ime 4 laravel

我的网站有评论。这些评论可以有“投票”、赞成票和反对票。

我有一个 Comment 模型和 CommentVote 模型。

在我的评论模型中,我有一个返回投票的函数:

public function votes() {
    return $this->hasMany('App\CommentVote', 'comment_id');
}

public function upvotes() {
    return $this->hasMany('App\CommentVote', 'comment_id')->where('vote', 1);
}   

public function downvotes() {
    return $this->hasMany('App\CommentVote', 'comment_id')->where('vote', -1);
}       
Run Code Online (Sandbox Code Playgroud)

请注意,赞成票以tinyInt 形式存储在数据库中1,反对票则存储为-1

在我的CommentVote模型中,我有belongsTo关系:

public function comment() {
    return $this->belongsTo('App\Comment');
}   
Run Code Online (Sandbox Code Playgroud)

现在我想要一个函数来计算评论的总“分数”。总赞成票减去总反对票。

我尝试创建一个函数来计算所有赞成票 - 所有反对票。

public function score() {
    return $this->upvotes()->count() - $this->downvotes()->count();
}   
Run Code Online (Sandbox Code Playgroud)

这会返回错误:

App\Comment::score 必须返回一个关系实例。

事实上,使用count()任何地方都会返回此错误,尽管它在我的其他模型中运行良好。

做一些简单的事情,比如:

public function voteCount() {
    return $this->hasMany('App\CommentVote', 'comment_id')->count();
    or even
    return $this->votes()->count();
}   
Run Code Online (Sandbox Code Playgroud)

将返回错误:

App\Comment::voteCount 必须返回一个关系实例。

为什么会发生这种情况?

编辑:

这是控制器,根据评论中的要求:

public function getSubmission($subchan, $id, $URLtitle) {

    $submission = Submission::where('id', $id)->first();
    $comments = Comment::where('submission_id', $submission->id)->where('parent_id', NULL)->orderBy('created_at', 'desc')->get();

    $comments = $comments->sortByDesc(function($comment){
        return count($comment['upvotes']) - count($comment['downvotes']);
    });     

    if (!$submission) {
        return redirect()->route('home')->with('error', 'Submission not found.' );
    }       

    return view('submissions.submission')
    ->with('submission', $submission)
    ->with('navSubchan', $submission->getSubchan->name)
    ->with('submissionPage', 1)
    ->with('comments', $comments)
    ;

}   
Run Code Online (Sandbox Code Playgroud)

cee*_*yoz 7

我怀疑你正在做的$model->score,它将寻找一个名为 的函数score(),但以一种特定的方式期望该函数返回HasMany,HasOneBelongsTo样式的关系对象。

请考虑使用访问器函数

public function getScoreAttribute() {
    return $this->upvotes()->count() - $this->downvotes()->count();
}
Run Code Online (Sandbox Code Playgroud)

让您做事$model->score成功。