laravel中的过滤器关系

时间:2020-09-26 08:08:25

标签: php laravel

我有具有hasMany关系的Posts and Comments模型:

public function comments()
{
    return $this->hasMany(Posts::class, 'posts_id', 'id');
}

在我的控制器中,我需要获取所有已发布的帖子(is_published = 1),其中包含所有已发布的评论,并且至少具有1个已发布的评论:

$dbRecords = Posts::all()->whereStrict('is_published', 1);
$posts = [];
foreach ($dbRecords as $post) {
    if (count($post->comments()) === 0) {
        continue;
    }

    foreach ($post->comments() as $comment) {
        if ($comment->is_published === 1) {
            $posts[] = $post;

            continue(2); // to the next post
        }
    }
}

但是,这样的解决方案很难看。另外,我将获得所有已发布的帖子,机智已发布和未发布的评论,因此我将不得不再次在Resource中过滤评论。

我发现的另一种解决方案-使用原始查询:

$dbRecords = DB::select("SELECT posts.* 
    FROM posts
    JOIN comments ON posts_id = posts.id
    WHERE posts.is_published = 1
      AND comments.is_published = 1
    HAVING count(posts.id) > 0;");
$users = array_map(function($row) { return (new Posts)->forceFill($row); }, $dbRecords);

但是它不能解决需要过滤Resource中未发表评论的问题。

2 个答案:

答案 0 :(得分:1)

如果您是这样的话。

whereHas

答案 1 :(得分:0)

如何雄辩

$posts = Post::query()->where('is_published', 1)->with(['comments' => function ($query) {
        $query->where('is_published', 1);
}])->get();