I am working with Laravel and have created a morphable comment table with laravel. Now I want to implemnt the reply function so people can answer to comments. I only do need the first level of answering. So, you can answer a comment but you cannot answer on a comment child. There is only one level of comment childs and not 2 or 3 like on Facebook.
My question to you now is, which is the best way to solve this. Because in my laravel view blade I am looping through each comment and want to print my child comments on this commment to (I just don’t know how do to his?).
So basically, I would like to know how you would design the table, how you would map it and how you would print it in the view.
Here is my table so far:
CREATE TABLE `comments` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `commentable_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `commentable_id` bigint(20) unsigned NOT NULL, `user_id` bigint(20) unsigned NOT NULL, `post_status_id` bigint(20) unsigned NOT NULL DEFAULT '4', `content` text COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), KEY `comments_commentable_type_commentable_id_index` (`commentable_type`,`commentable_id`), KEY `comments_user_id_index` (`user_id`), KEY `comments_post_status_id_index` (`post_status_id`), CONSTRAINT `comments_post_status_id_foreign` FOREIGN KEY (`post_status_id`) REFERENCES `post_statuses` (`id`) ON DELETE CASCADE, CONSTRAINT `comments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Advertisement
Answer
Child comments should just be more comments except they are mapped to another comment.
Create a comment_children table.
Structure should be:
id: BIGINT comment_id: BIGINT child_id: BIGINT
Then you can create a hasManyThrough children relationship on your Comment model and use the comment_children table to match them.
This will allow you to eager load the child comments, you can make your mode always do this by adding:
protected $with = [‘children’]
You will also want a comments relationship on your PostStatus model.
Set up your model to always load this relationship also by adding:
protected $with = [‘comments’]
Now whenever you fetch a post, the collection will always contain all the comments and all the children.
Now to access it, something like:
$post = Post::where(‘id’, 1)->first()
And in your blade:
@foreach($post->comments as $comment) // display comment @foreach($comment->children as $child) // display child comments @endforeach @endforeach