Laravel数据透视表 - 从反向关系表访问


Laravel Pivot Tables - accessing from inverse relation-table

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

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


在我的数据库中,我有problem_ratings、问题和用户。我有用户和问题的模型,problems_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');

}

当在

这样的东西上使用foreach循环时,你需要使用动态属性(即不带括号):

foreach($problem->userRatings as $rating){而不是foreach($problem->userRatings() as $rating){