I have a tree structured model Group which has the columns id, parent_id, name, lft and rght. I also have a model User which has the columns id, name and password. Group and User have a Has-and-Belongs-to-Many (HABTM) relationship using the join-table groups_users
I want to create a view that creates a new tree which includes all the groups and all the users as children of the groups they belong to. The view should have the columns id, parent_id, model, foreign_key, lft and rght.
The id column should just be the Nth row and parent_id, lft and rght can't be just copied from the Group model, they will have to calculated for the tree of the view.
An example of what the view could look like:
| id | parent_id | model | foreign_key | lft | rght
----------------------------------------------------
| 1 | NULL | Group | 1 | 1 | 14
| 2 | 1 | User | 1 | 2 | 3
| 3 | 2 | Group | 2 | 4 | 7
| 4 | 3 | User | 3 | 5 | 6
| 5 | 4 | Group | 3 | 8 | 13
| 6 | 5 | User | 2 | 9 | 10
| 7 | 5 | User | 4 | 11 | 12
| 8 | NULL | Group | 4 | 15 | 20
| 9 | 8 | User | 4 | 16 | 17
| 10 | 8 | User | 5 | 18 | 19
How do I do this?
Can it be done with some super complex SELECT statement or do I need to use a procedure?
I'm not super skilled at MySQL; I can do simple SELECTs and JOINs, but this is way beyond my skill level.
