【发布时间】:2020-06-28 22:48:24
【问题描述】:
我正在构建一个 laravel 网站。它有提交,提交有 cmets。我想急切地加载这些 cmets 及其子 cmets(以及那些评论的子代等)。但只是在一定程度上。
子评论循环仅在 $loop->depth 10 和 $loop->iteration 8 内加载子 cmets。我不想急切加载我什至不会显示的 cmets。
这是我目前所拥有的:
控制器:
$repliesCount = Comment::with([
'owner',
'savedComments',
'votes',
])
->where('submission_id', $submission->id)
->whereNotNull('parent_id')
->count();
$comments = Comment::where('submission_id', $submission->id)
->whereNull('parent_id')
->with([
'owner',
'savedComments',
'votes',
'submission',
'reports'
])
->orderBy('removed', 'asc')
->orderBy($sortBy, $direction)
->paginate(100);
$replies = Comment::where('submission_id', $submission->id)
->whereNotNull('parent_id')
->with([
'owner',
'savedComments',
'votes',
'submission',
'reports'
])
->orderBy('removed', 'asc')
->orderBy($sortBy, $direction)
->paginate($repliesCount);
$comments_by_id = new Collection();
$replies_by_id = new Collection();
foreach ($comments as $comment) {
$comments_by_id->put($comment->id, $comment);
$comments_by_id->get($comment->id)->children = new Collection();
}
foreach ($replies as $reply) {
$replies_by_id->put($reply->id, $reply);
$replies_by_id->get($reply->id)->children = new Collection();
}
foreach ($replies as $key => $reply) {
if ($comments_by_id->get($reply->parent_id)) {
$comments_by_id->get($reply->parent_id)->children->push($reply);
} elseif ($replies_by_id->get($reply->parent_id)) {
$replies_by_id->get($reply->parent_id)->children->push($reply);
}
}
刀片:
@foreach ($comment->children as $comment)
@if ($loop->depth == 10)
<div>
<a href="{{ route('get.submission', ['subchan' => $comment->submission->subchan, 'id' => $comment->submission->id, 'URLtitle' => $comment->submission->URL_title,'commentID' => $comment->parent_id]) }}">Continue this thread</a>
</div>
@break
@endif
<div class="comment-container comment-container-child" id="comment-container-{{$comment->id}}" hidden-level="{{ceil(($loop->iteration + 3) / 10) - 1}}">
@include('partials.comment_block')
</div>
@if ($loop->iteration % 10 == 7 && $loop -> remaining > 0)
<div class="loadMoreReplies comment-container-child load-more"
hidden-level="{{ceil(($loop->iteration + 3) / 10) - 1}}"
data-submission-id="{{ $comment->submission->id }}"
data-parent-id="{{$comment->parent_id}}"
>Load More Replies (<span id="remaining-reply-count-{{$comment->parent_id}}">{{ $loop->remaining }}</span>)</div>
@endif
@endforeach
基本上,我需要 100 cmets ($comments),并且我渴望加载我需要的关系(例如“所有者”关系)。
然后我进行查询以获取该提交 ($replies) 及其所有关系的所有子 cmets。
之后,我创建了一个集合,将每个子回复推送到其父 comment->children。
这行得通。但是,它会加载给定评论的所有儿童回复。因此,即使我只加载 100 个父 cmets,如果其中一个 cmets 或子 cmets 有 THOUSANDS 子 cmets,它也会一次性加载所有这些。
这里有一张图片可以更好地说明(5000 条回复被隐藏但仍在被查询,因此页面加载需要很长时间):
我最终想要的是它只渴望加载并返回最多 10 个子 cmets,同时还传递评论有多少孩子,以便我可以显示缺少多少孩子。
【问题讨论】: