我有三张 table
common_addons。
hotel_addons。
菜单
ID common_addons
是属性common_addons_id
的foreign_key在hotel_addons
和 ID hotel_addons
是属性hotel_addons_id
的foreign_key在表中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');
我要common_addons
的name
通过表menu
,其中包含属性 hotel_addons_id
。属性 hotel_addons_id
包含多个ids
hotel_addons 的数量,以逗号分隔(通过 Implode 函数)。
最佳答案
这就是你现在拥有的
menu
--------------
id 1
hotel_addons_id 1,2,3,4
与其说这是一个“答案”,不如说它是在解释 ManyToOne 和 OneToMany 如何构成 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
在桥接表中,主键是两个外键的复合键,每个外键都是一个代理键(自动递增)。
换句话说,一个菜单可以有很多插件,而插件可以属于很多菜单项。你现在拥有的方式是一个糟糕的黑客,永远不会给你你需要的东西。
您不能加入逗号分隔的列表(至少不容易)。做这样的事情要容易得多:
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
等等...
关于php - 使用外键和多对一连接三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44796829/