I have a comment system on 2 levels (like Blizzard http://eu.battle.net/sc2/en/blog/7935264/#c-7257875753), it's working fine but my code is a bit dirty :
// $datacoms array from mysql_query
foreach($datacoms as $com){
if(!$com->parent_id){
$level_id = $com->id;
// include the view (display the comment)
foreach($datacoms as $com){
if($com->parent_id == $level_id){
// include the view (display the comment)
}
}
}
}
Any better way to do it ?
1 Answer 1
Depends on how your data is modeled. I dont know that, but I can assume that you use three relational tables. Something along these lines:
Post [parent]
+-------------+---------+
| Field | Type |
+-------------+---------+
| id | int |
| value | varchar |
+-------------+---------+
Comment [parent-child]
+-------------+---------+
| Field | Type |
+-------------+---------+
| id | int |
| foreign_key | int |
| value | varchar |
+-------------+---------+
Comment->Comment [child]
+-------------+---------+
| Field | Type |
+-------------+---------+
| id | int |
| foreign_key | int |
| value | varchar |
+-------------+---------+
You are looking to potentially run three queries. An easy fix would be to add a has_children field to each parent table. With that you would save a potential checkup and easily release some complexity in the PHP loop.
[parent-child]
+--------------+---------+
| Field | Type |
+--------------+---------+
| id | int |
| foreign_key | int |
| has_children | bool | <===
| value | varchar |
+--------------+---------+
I can provide the PHP code if you like, but I'm assuming that you get the general idea.