Search code examples
phpmysqlschemacakephp-2.0rdbms

better way to handle multiple tables relationship


Suppose i have some tables like...
countries

id name  
1  Cyprus  
2  India   

states

id name country_id   
1   a     1   
2   b     2   
3   c     2  

cities

id name state_id   
1   x     1     
2   y     2  
3   z     3  
4   p     2    

pages

id name  slug    status   
1   ab   a-b       1      
2   pq   p-q       0   
3   abc  a-b-c     1     

mode_of_training

id  name 
1   Virtual
2   Classroom

items

id name description 
1   a   something   
2   b   something

prices

id price currency_code 
1   200   USD
2   300   AUD
3   4000  INR

offers

id name   discount
1  xyz-1   20%
2  abc-2   30%
3  pqr-3   10%

Creating table structure in that way is correct?? so that i can reuse them using there ids.

For example

items_relation_table

id country_id state_id  city_id  page_id item_id price_id offer_id  status
1   0           0         0       1        1       1         0        1
2   0           0         0       1        1       1         1        0
3   1           0         1       2        2       1         2        1
4   1           0         1       3        3       2         1        1 
  • Now i don't need to use field values of tables
  • If i want to change price. i'll change price in one place only
  • I'm saving number of bytes.
  • database table size is less

But my problem is To fetch data i need to use Joins
Or Creating View is better idea
Or There is any Better way to create table structure


Solution

  • Your entity-tables look fine at the first glance. But I don't understand your relation table. Looks like you try to relate everything with everything, which in some cases probably doesn't make sense (do offers really belong to countries?) in in some cases it seems redundant: When a page is linked to (many) cities, there is no need to link it to the countries too, because the countries are determined by the cities.

    You should add relation-tables only between those entities that really need to be in a direct many-to-many relation. And for each of those relations you need a separate table.

    e.g. for a relation between pages and cities:

    cities(id, name, state_id) <--> cities_pages(city_id, page_id) <--> pages(id, name, slug, status)
    

    And yes, you have to join tables to fetch data. Thats one of the basic ideas behind relational databases. Don't be afraid of joins, if your tables are properly indexed thats not an expensive operation at all (assuming that performance is your concern). And of course you could add some views if that makes sense for your application, but that will include the same JOINS you would just abstract them behind CREATE VIEW statements.