Laravel 在急切加载关系上使用 where

Laravel using where on eager loaded relationship

您好,我有以下代码可以检索所有 post 以及他们的评论(一对多关系)

$posts = Post::with('comments')->get();

现在效果很好,但我的问题是如果给定可选参数,我想搜索 post 标题或评论内容。类似于:

$posts = Post::with('comments');

if (Request::has('query')) {
    $posts = $posts->where('content', 'LIKE', '%' . Request::get('query'))->orwhere('title', 'LIKE', '%' . Request::get('query'));
}

$posts = $posts->get();

现在这不起作用,因为 'content' 列仅存在于评论 table 中。有什么方法可以在急切加载的评论关系上使用 where 条件吗?

在构建查询时使用 whereHas(),文档中的示例:

$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

Docs link

使用orWhereHas() and orWhere():

$posts = Post::with('comments');

if (request()->has('query')) {
    $posts = $posts->orWhereHas('comments', function($q) {
        $q->where('content', 'like', '%'.request('query'));
    })->orWhere('title', 'like', '%'.request('query'));
}

$posts = $posts->get();

测试一下。如果你想改变行为,你可以在 if() 结构中使用 whereHas() and/or where()

使用Constraining Eager Loads

if (request()->has('query')) {
    $posts = Post::where('title', 'LIKE', '%' . Request::get('query'))->with(['comments' => function ($query) {
        $query->orWhere('content', 'LIKE', '%' . Request::get('query'));
    }]);
} else {
    $posts = Post::with('comments');
}

$posts = $posts->get();

我认为@Alexey Mezenin 的回答不正确,结果将是所有带有评论的帖子。