gpt4 book ai didi

使用 Laravel 的 PHP 评论系统

转载 作者:行者123 更新时间:2023-12-02 08:23:00 37 4
gpt4 key购买 nike

我正在使用 laravel PHP 开发一个网站,并尝试使用以下结构做一个评论系统:

- Comment 1 (id = 1)
-- Reply 1 (id = 2) (parent_id = 1)
--- Reply 2.1 (id = 3) (parent_id = 2)
-- Reply 2 (id = 4) (parent_id = 1)

我想知道如何做一个 foreach 来覆盖它?因为我不知道一条评论会有多少条子评论。

最佳答案

不会将评论和回复存储在单独的表中,因为它们在一天结束时都是评论实体。只需在您的 comments 表中包含一个 parent_id 列,您就可以在一个数据库查询中获取评论和回复,而不是两个。

我假设您还有一个外键将评论链接到帖子之类的东西。然后,您可以获取该帖子 ID 的所有评论:

$comments = Comment::latest()->where('post_id', '=', $post->id)->get();

然后根据它们的 parent_id 值对它们进行排序:

$comments = $comments->keyBy('parent_id');

然后您可以像这样在您的 Blade 模板中迭代它们,并且每次迭代时,检查是否有以该评论的 ID 作为其父 ID 的评论:

<!-- Kick-start the loop -->
@foreach($comments[0] as $comment)
@include('partials.comment')
@endforeach

partials/comment.blade.php的内容

<blockquote class="comment">
<p class="comment-body">{{ $comment->body }}</p>
<footer>
<span class="comment-author">{{ $comment->user->name }}</span>,
<time class="comment-date" pubdate="pubdate">{{ $comment->created_at }}</time>
</footer>
</blockquote>

@if(isset($comments[$comment['id']])
@each('partials.comment', $comments[$comment['id'], 'comment')
@endif

关于使用 Laravel 的 PHP 评论系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012375/

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