本文介绍了带有Laravel Commentable/嵌套集的递归儿童的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Laravel Commentable 来获取所有递归子级.截至目前,我可以得到第一个这样的孩子:

I am trying to get all the recursive children using Laravel Commentable. As of now, I can get the first children like this:

$user->comments()->with(['creator', 'children.creator'])->where('parent_id', null)->get()

但这不是递归的",我必须一遍又一遍地这样做: children.children.children 等.如何获取所有注释及其各自的子对象,以便以JSON形式返回?

But this isn't "recursive" and I'd have to do it over and over: children.children.children etc. How do I get all comments and their respective children so I can return it as JSON?

示例输出:

{
  "comments": [
    {
      "id": 1,
      "body": "foo",
      "children:" 
        {
          "id": 5,
          "body": "foo",
          "children:"
            {
              "id": 5,
              "body": "foo",
              // etc
            }
        }         
    }
}

推荐答案

我最终检索了所有注释 $ user-> comments ,然后像这样对它们进行排序/排列:

I ended up retrieving all comments $user->comments and then sorting/arranging them like this:

public static function arrange($comments)
{
    $comments->transform(function ($comment) use ($comments) {
        $comment->children = $comments->where('parent_id', $comment->id);
        return $comment;
    });

   return $comments->reject(function ($comment) {
        return $comment->parent_id !== null;
    });
}

这篇关于带有Laravel Commentable/嵌套集的递归儿童的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 08:20