php - Laravel 中的过滤关系

标签 php laravel

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

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

在我的 Controller 中,我需要获取所有已发布的帖子 (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
        }
    }
}

但是,这样的解决方案很丑陋。另外,我将获得所有已发布的帖子,包括已发布和未发布的评论,因此我将强制在资源中再次过滤评论。

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

$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中未发表评论需要过滤的问题。

最佳答案

在你的情况下,它会是这样的:

// Retrieve all posts that have at least one comment
$posts = Post::has('comments')->with('comments')->get();

// Retrieve posts with at least one comment and which are published
$callback = function($query) {
    $query->where('is_published ', '=', '1');
}

$posts = Post::whereHas('comments', $callback)
    ->with(['comments' => $callback])
    ->where('is_published ', '=', '1')
    ->get();

关于php - Laravel 中的过滤关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64075342/

相关文章:

javascript - yii2 ajax 验证表格

laravel - laravel 中哪里可以设置标题

php - 在 laravel 5.4 中,我怎样才能只获得用户 friend 的帖子?

php - 查询 MySQL 数据库时得到一个空集

php - 如何将表单数据插入MySQL数据库表

php - 在 php 中获取文件 mime 类型的最佳方法

php - 使用自定义元键和元值扩展 wc_get_orders()

php - Laravel Blade 中 Controller 的多对多关系访问值

mysql - 如何在laravel中生成唯一的序列号

mysql - 将我的原始 sql 转换为 Eloquent 代码时出错