Double Relationship With One Table in PHP
Let's say we have cities:
id | name |
---|---|
1 | city1 |
2 | city2 |
3 | city3 |
Let's say we have routes between cities, where each route has a starting city and an ending city:
id | name | from_city_id | to_city_id |
---|---|---|---|
1 | route1 | 1 | 2 |
2 | route2 | 2 | 3 |
Suppose we want to get routes along with cities. The complexity here is that each route has two cities: start and end.
It turns out that the table with cities needs to be joined twice. With each join, the table will have to be renamed:
SELECT
from_cities.name as from_city_name,
to_cities.name as to_city_name
FROM
routes
LEFT JOIN cities as from_cities
ON from_cities.id=routes.from_city_id
LEFT JOIN cities as to_cities
ON to_cities.id=routes.to_city_id
Suppose we have users. Each user has a father and a mother. Describe the storage structure.