my table looks like
CREATE TABLE `test_comments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` int(10) unsigned DEFAULT NULL,
`test_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`comment` mediumtext COLLATE utf8_unicode_ci NOT NULL,
`rate` mediumint(9) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `test_comments_user_id_foreign` (`user_id`),
KEY `test_comments_test_id_foreign` (`test_id`),
KEY `test_comments_parent_id_foreign` (`parent_id`),
CONSTRAINT `test_comments_parent_id_foreign` FOREIGN KEY (`parent_id`) REFERENCES `test_comments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `test_comments_test_id_foreign` FOREIGN KEY (`test_id`) REFERENCES `tests` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `test_comments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
how can i retrieve comments like this structure:
[
{
"id": 3,
"comment": "...",
"comments": [
{
"id": 12,
"comment": "answer for #3",
"comments": []
},
{
"id": 14,
"comment": "answer for #3",
"comments": [
{
"id": 22,
"comment": "sub comment for #14",
"comments": [
{
"id": 23,
"comment": "discussion continues..."
}
]
}
]
},
]
},
{
"id": 44,
"comment": "wow so many comments!",
"comments": []
}
]
I had an idea to form this structure in the application layer, but I think that this will negatively affect the memory consumption and the load as a whole.
I do not know how others solve such problems and i have not yet found a solution. I will be grateful if the community will tell me the right way :)