- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我使用的php框架是Laravel。我有一个评论表,评论允许有子评论。我按更新时间对评论进行了排序:
$post->comments()->orderBy('updated_at')->paginate(10);
现在我想对评论进行分组,以便将具有相同父评论的所有子评论放在一起,即父评论,然后是其所有子评论,然后是下一个父评论,然后是其所有子评论一一评论等等,如下:
现在这个订单不能通过简单的“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 个评论,第一个评论是由 User
与 user_id-1
发表的,并且有两个子评论是由其他两个发表的id
为 user_id-2
和 user_id-3
的用户。
此处,comment_parent
列保留父
和子
评论之间的关系。值为0
的comment_parent
是父评论,并且不是0
,例如这里两条评论都有comment_parent
> of 1
这意味着这两个评论是 id/PK
为 1
的评论的子评论。
现在,在您的 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/
我是一名优秀的程序员,十分优秀!