Multiple Descendants in Family Relationships in PHP
In the previous lesson, a father could only have
one son. This was achieved because
the father had a relation son_id.
Now let a father have several sons.
In this case, we can still make
only one table, which will be related
to itself. Only in the relation field we will store
not the id of the son, but the id of the father. In this
case, several users will be able to reference
their father - and thus the father will have
several sons:
| id | name | father_id |
|---|---|---|
| 1 | user1 | 3 |
| 2 | user2 | 3 |
| 3 | user3 | 4 |
| 4 | user4 | null |
You can get a user along with his father as follows:
SELECT
users.name as user_name,
fathers.name as father_name
FROM
users
LEFT JOIN users as fathers ON fathers.id=users.father_id
Suppose we have users. Each user has a father and a mother. Describe the storage structure.
Write a query that will fetch a user along with his father and mother.