更新:显然$problem->userRatings()->count();返回1,所以一条记录确实存在,但是由于某种原因该脚本仍然没有进入foreach循环...

更新2 /解决方案:我感到非常愚蠢,但是它不起作用的原因是我在foreach($problem->userRatings() as $rating){应该是foreach($problem->userRatings as $rating){时调用了它(动态属性)



在我的数据库中,我有问题评分,问题和用户。我有针对用户和问题的模型,而problem_ratings是问题和用户之间的数据透视表,带有一个额外的“内容”列,用于存储数字评分值(1-5)。

我的问题模型中的多对多关系:

public function userRatings(){
    return $this->belongsToMany('User', 'problem_ratings', 'author_id', 'problem_id')->withPivot('content');
}


我的用户模型中的多对多关系:

public function problemRatings(){
    return $this->belongsToMany('Problem', 'problem_ratings', 'author_id', 'problem_id')->withPivot('content');
}


当创建一个problem_ratings元素时,我将其附加到我的用户模型中,如下所示:

$user->problemRatings()->attach($problem->id, array('content' => $val));


我可以通过用户访问数据透视表,但是当我尝试这样做时:

foreach($problem->userRatings() as $rating){
    echo "In average loop";
    $newAverage = ($rating->pivot->content) + $newAverage;
}


即使数据库中存在某些记录,它也找不到任何记录。我是否正确使用这些关系?

提前致谢!

最佳答案

在问题模型中,我认为您的关系应类似于:

public function userRatings(){
return $this->belongsToMany('User', 'problem_ratings', 'problem_id', 'author_id')->withPivot('content');


}

10-04 21:26
查看更多