I have the following simplified database table structure for a legacy tickets-like system.
messages
id INT
parent_id INT
content TEXT
answer TEXT
...
On a list, I show all the messages. When a message is clicked, I display its answer etc.
The problem is, now I need to make a list structure of all parents and children related to this message, as well as the position of this message in the tree. How could I retrieve those from database?
I'm using Laravel, but raw SQL would also help me find the direction.
Example:
╔════╦═══════════╦════════════════════════╦═════════════════╗ ║ id ║ parent_id ║ content ║ answer ║ ╠════╬═══════════╬════════════════════════╬═════════════════╣ ║ 1 ║ NULL ║ Hi, I have a problem ║ I can't help ║ ║ 2 ║ 1 ║ The problem persists ║ Ok, what is it? ║ ║ 3 ║ 2 ║ Nevermind, I got this ║ Oh, well. ║ ║ 4 ║ 3 ║ Problem is back ║ Which problem? ║ ║ 5 ║ 4 ║ The same problem again ║ ... ║ ╚════╩═══════════╩════════════════════════╩═════════════════╝
When showing message with id = 4
, I should be able to display something like this list:
Message history:
- Hi, I have a problem
- The problem persists
- Nevermind, I got this
- Problem is back
- The same problem again
I could only think of a loop and several SQL query executions, for each parent and child, which looks like a code smell.
UPDATE
As stated by Daan, this question seems like a duplicate for How to create a MySQL hierarchical recursive query.
I decided to not delete it however, since Ravan just answered it with a Laravel approach that helped me solve the problem, so I'll just leave this here for future reference.