Laravel:查询一个多对多的关系,如果第二个表中的condition不为true,则在第一个表中捕获行

r9f1avp5  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(59)

我有两个表postsemployees,它们有多对多的关系。
现在我想查询所有的职位在透视表'用户_id'是logedin userstatusAccepted;
这是我的疑问

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.
我希望解释得很好。

yizd12fk

yizd12fk1#

with传递一个Closure指定要加载哪些相关模型(Employee),但不会过滤您正在查询的模型(Post)。
要添加该过滤器,需要使用whereHas(relation, Closure)

$posts = Post::query()
    ->whereHas('employee', function ($rel) {
        $rel->where('your_pivot_table_name.status', 'Accepted')
            ->where('user_id', Auth::id());
    })
    ->with([
        'address',
        'service',
        'employees' => function ($rel) {
            $rel->wherePivot('status', 'Accepted')
                ->where('user_id', Auth::id());
        }
    ])
    ->orderByDesc('created_at')
    ->paginate(10);

相关问题