【问题标题】:Get comment sub-comments when only one sub-comment只有一个子评论时获取评论子评论
【发布时间】:2020-01-09 16:22:18
【问题描述】:

我有 cmets 表,其中有 parent_id
这是评论表sub_comments 关系。

public function sub_comments()
{
    return $this->hasMany(self::class, 'parent_id');
}

此代码返回所有 cmets 以及相关的所有子 cmets

Comment::with('sub_comments')->get(); 

但是当 sub-cmets 是单一的时,我希望所有的 cmets 也都是 sub-cmets。这意味着如果评论有 2 个或更多的 cmets,我不想得到那个子 cmets。 现在我使用这段代码

$oneSubcommentCommentIds = Comment::has('sub_comments', '=', 1)->pluck('id');
Comment::with([
    'sub_comments' => function ($q) use ($oneSubcommentCommentIds) {
        $q->whereIn('parent_id', $oneSubcommentCommentIds);
    }
])->get();

但这会产生一个额外的查询。

【问题讨论】:

  • 所以您想加载所有 cmets,但如果只有一个 sub_comment,则只加载关系 sub_comments?这没有意义,并且您无法确定关系的计数不加载关系...
  • 是的,你是对的

标签: php laravel laravel-5 eloquent laravel-5.8


【解决方案1】:

试试这个:

Comment::with('sub_comments')->has('sub_comments', '=', 1)->get(); 


更新

你的问题不清楚,如果没有预先加载关系或关系的计数,我无法想象另一种方法。所以我会这样做:

// First get all your comments with an aditional count field
$comments = Comments::withCount('sub_comments')->get();

// separate the ones with just one sub_comment from the rest
list($oneSubComment, $theRest) = $collection->partition(function ($comment) {
    return $comment->sub_comments_count == 1;
});

// Then load the relationship on just the selected elements
$oneSubComment->load('sub_comments');

// re-join the collection
$comments = $oneSubComment->union($theRest);

我在这里做什么?

  1. 使用relationship count 向每个$comment 添加一个附加字段(应该类似于sub_comments_count
  2. 将生成的集合分为两部分:带有一条注释的部分和其余部分。使用partition() 方法。
  3. Lazy eager loading 收藏。
  4. 使用union() 方法重新加入两个集合。

【讨论】:

  • 这只能获取包含一个子评论的 cmets。但我想得到所有的cmets
  • @Davit 我已经更新了我的答案。我尚未对其进行测试,但它应该可以工作,或者至少可以指导您获得所需的输出。
  • 您的解决方案必须有效,但这也是进行 2 次查询。我只想使用 1 个查询
  • 是的,我也想知道如何在一个查询中执行此操作,但我无法想象如何。您也可以只加载所有 cmets 的关系,然后将它们隐藏在您的视图中以满足您的需求。
  • 我测试你的代码。它正在工作(赞成)。但我更喜欢优化查询并只进行 1 次查询
猜你喜欢
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 2016-11-30
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
相关资源
最近更新 更多