Mysql 如何在Laravel 5中的一对多关系中仅查询一个外行
我有4种模式:Mysql 如何在Laravel 5中的一对多关系中仅查询一个外行,mysql,laravel,laravel-5,Mysql,Laravel,Laravel 5,我有4种模式:帖子,用户,类别,用户类别 帖子-用户具有一对多关系(一篇帖子属于一个用户) 帖子-类别具有一对多关系(一篇帖子属于一个类别) 用户-用户类别具有一对多关系(一个用户具有多个用户类别)。userCategory有一个rank字段,用于保存特定类别的用户性能 $rank_of_the_post_owners = array(); foreach($posts as $post) foreach($post->user->userCatergories as $us
帖子
,用户
,类别
,用户类别
帖子
-用户
具有一对多关系(一篇帖子属于一个用户)
帖子
-类别
具有一对多关系(一篇帖子属于一个类别)
用户
-用户类别
具有一对多关系(一个用户具有多个用户类别)。userCategory有一个rank
字段,用于保存特定类别的用户性能
$rank_of_the_post_owners = array();
foreach($posts as $post)
foreach($post->user->userCatergories as $userCategory)
if($userCategory->id == $post->category_id) {
$rank_of_the_post_owners [$post->id] = $userCategory->rank;
break;
}
}
}
我对一些帖子进行了如下查询:
$posts = Post::with(array('user.userCategories')
)
->where('category_id', '=', $category_id)
->get();
在评估帖子之后,我尝试获取用户对帖子类别的userCategoryrank
$rank_of_the_post_owners = array();
foreach($posts as $post)
foreach($post->user->userCatergories as $userCategory)
if($userCategory->id == $post->category_id) {
$rank_of_the_post_owners [$post->id] = $userCategory->rank;
break;
}
}
}
为了摆脱上面的代码,我只想查询相关的userCategory(针对帖子的类别)。因此,我想访问排名信息,比如user.userCategory->rank,而不是循环
如何才能做到这一点?使用with()
时,您可以通过使用闭包作为值来约束关系,并且由于您已经拥有$category\u id
,您可以执行以下操作:
$posts = Post::with(['user.userCategories' => function ($query) use ($category_id) {
$query->where('userCategories.id', $category_id);
}])
->where('category_id', '=', $category_id)
->get();
然后,如果您愿意,您可以添加访问器以获取帖子的排名:
public function getRankAttribute()
{
return $this->user->userCategories->sum('rank');
}
因此,要访问排名,您只需:
$posts->first()->rank;
希望这有帮助