简体   繁体   中英

Connect three tables with foreign key and many to one

I have three tables

  1. common_addons.

  2. hotel_addons.

  3. menu

id of common_addons is foreign_key of attribute common_addons_id in hotel_addons and id of hotel_addons is foreign_key of attribute hotel_addons_id in table menu .

        $this->db->join('hotel_addons', 'hotel_addons.id = menu.addon_id');
        $this->db->join('common_addons', 'addons.id = hotel_addons.addons_id');
        $this->db->from('menu');
        $this->db->join('menu', 'menu.addon_id = hotel_addons.id');

I want common_addons 's name through table menu , which contains attribute hotel_addons_id . attribute hotel_addons_id contains multiple ids of hotel_addons seprated by commas(through Implode function).

This is what you have now

menu
--------------
id                           1
hotel_addons_id              1,2,3,4

This is not an "Answer" so much as it is explaining how a ManyToOne, and a OneToMany, can make a ManyToMany

hotel_addons
--------------
id                           1        //one to many - one addon has many records in the bridge table

menu_hotel_addons  (bridge table)  = many to many
-------------------------
menu_id                        1     //many to one  - many bridge records point to the menu
hotel_addons_id                1     //many to one  - many bridge records point to the addons table

 menu
 --------------
id                           1     //one to many  - one menu has many records in the bridge table

In the bridge table the Primary key is a compound key of both foreign keys, each foreign key, is a surrogate key ( auto increment ).

In other words a Menu can have many addons, and addons can belong to many menu items. The way you have it now, is a poor hack that will never give you what you need.

You cannot join on a comma separated list ( not easily at least ). Its much easier to do something like this:

     SELECT 
        m.*,
        a.*
     FROM
         menu AS m
     JOIN
          menu_hotel_addons AS ma
     ON 
        m.id = ma.menu_id
     JOIN
        hotel_addons  AS a
     ON
        ma.hotel_addons_id = a.id

Etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM