我有两个表posts
和employees
,它们有多对多的关系。
现在我想查询所有的职位在透视表'用户_id'是logedin user
和status
是Accepted
;
这是我的疑问
public function accepted()
{
$posts = Post::with(['employees' => function ($q) {
$q->wherePivot('status', 'Accepted')
->where('user_id', Auth::id());
}])
->with('address', 'service')
->orderBy('created_at', 'DESC')
->paginate(10);
return response()->json($posts);
}
如果你看下图,所有的帖子都返回了,即使数据透视表中的条件不为真。
上图中;有两行,在第一行employees []
是空的,我不想被返回.和第二行必须只返回,因为条件'employees.pivot' true.
我希望解释得很好。
1条答案
按热度按时间yizd12fk1#
向
with
传递一个Closure指定要加载哪些相关模型(Employee
),但不会过滤您正在查询的模型(Post
)。要添加该过滤器,需要使用
whereHas(relation, Closure)