gpt4 book ai didi

mysql - Laravel深度优先树遍历

转载 作者:行者123 更新时间:2023-11-29 23:41:58 24 4
gpt4 key购买 nike

所以我使用的php框架是Laravel。我有一个评论表,评论允许有子评论。我按更新时间对评论进行了排序:

$post->comments()->orderBy('updated_at')->paginate(10);

现在我想对评论进行分组,以便将具有相同父评论的所有子评论放在一起,即父评论,然后是其所有子评论,然后是下一个父评论,然后是其所有子评论一一评论等等,如下:

  • 评论1
  • 评论1的子评论A
  • 评论1的子评论B
  • 评论2
  • 评论2的子评论C
  • 评论2的子评论D
  • 子评论D的子评论E
  • ...

现在这个订单不能通过简单的“orderBy”来完成,我的问题是:我可以使用 Laravel 查询构建器/eloquent 来完成这个订单,还是必须手动订购?顺便说一句,我已经设置了 Comment 模型,以便可以通过以下方式获取其父/子模型:

$comment->parentComment;
$comment->childComments;

最佳答案

您可以使用模型关系(自身)来实现此目的,例如,假设这是您的 comments 表:

id (PK) | content | post_id | user_id | comment_parent
------------------------------------------------------
1 | Hello | 1 | 1 | 0 <-- This is a parent because of 0
2 | Hi | 1 | 2 | 1 <-- child of 1
3 | Howdy | 1 | 3 | 1 <-- child of 1

将该表解读为:总共有 3 个评论,第一个评论是由 Useruser_id-1 发表的,并且有两个子评论是由其他两个发表的iduser_id-2user_id-3 的用户。

此处,comment_parent 列保留 评论之间的关系。值为0comment_parent是父评论,并且不是0,例如这里两条评论都有comment_parent > of 1 这意味着这两个评论是 id/PK1 的评论的子评论。

现在,在您的 Comment 模型中声明这些方法:

// Get only children of a comment
public function children()
{
return $this->hasMany('Comment', 'comment_parent');
}

// Get the user of comment
public function user()
{
return $this->belongsTo('User', 'user_id');
}

// Get the post of comment
public function post()
{
return $this->belongsTo('Post', 'post_id');
}

然后在您的 Post 模型中声明此方法:

// Only parent comments
public function comments()
{
return $this->hasMany('Comment', 'post_id')->where('comment_parent', 0);
}

// All Comments
public function allComments()
{
return $this->hasMany('Comment', 'post_id');
}

现在,如果你这样做:

$post = Post::with('comments.children')->find(1);

然后您可以在您的 View 中尝试类似的操作(可能在您的 post.single.blade.php 中):

{{ $post->title }}
{{ $post->body }}

<!-- Comment Template For Posting New Comments-->

@if($post->comments->count())

@foreach($post->comments as $comment)

{{ $comment->user->username }}
{{ $comment->body }}

@if($comment->children->count())

@foreach($comment->children as $childComment)

{{ $childComment->user->username }}
{{ $childComment->body }}

@endforeach

@endif

@endforeach

@endif

这是一个想法,在这种情况下,默认情况下,您的评论将 0 作为 comment_parent,当评论是对另一个评论的回复时,请将其设置为 >comment_parent 为其父级的 id。另外,您可以查看this article不同的方法。

关于mysql - Laravel深度优先树遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26120565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com