I've created a nested comment system that outputs comments in the following layout:
| Comment 1
| | Comment 2
| | | Comment 3
| | | | Comment 4
| | Comment 5
| Comment 6
| Comment 7
This works fine for a smaller number of comments, but it becomes a problem when there are hundreds or thousands.
One problem, for example, is that the depth of the comments gets too large, like this:
| Comment 1
| | Comment 2
| | | Comment 3
| | | | Comment 4
| | | | | Comment 5
| | | | | | Comment 6
| | | | | | | Comment 7
| | | | | | | | Comment 8
| | | | | | | | | Comment 9
| | | | | | | | | | Comment 10
| | Comment 11
| Comment 12
| Comment 13
This becomes an issue when displaying the comments to the user as it makes the page/comments harder to read.
What I want to do is limit the number of results at certain depths. For example, in the code snippet above, how would I make it show no more than 5 comments deep and then have a button that says "click for more comments" that reveals the rest of the comments?
Additionally, another problem is showing too many nested comments, like this:
| Comment 1 (top-level comment)
| | Comment 2
| | Comment 3
| | Comment 4
| | Comment 5
| | Comment 6
| | Comment 7
| | Comment 8
| | Comment 9
| | Comment 10
| Comment 11 (top-level comment)
| Comment 12 (top-level comment)
Obviously, for readability reasons, I don't want to show all of the nested comments for each top-level comment. So how could I limit the number of results shown to 5 as well?
I need to combine these two ideas to give me a reasonable way to query the database to form a comment tree.
Here is my current code. I have a Comment.php
model with the following relationship:
public function children()
{
return $this->hasMany('App\Comment', 'parent_id', 'id')->with('children');
}
parent_id
is the id
of the parent comment.
And to get a comment tree of all comments currently in the database, I do:
$comments = Comment::where('post_id', 1)
->where('parent_id', 0)
->with('children')
->get();
How can I change my code/query to get my desired output?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire