简体   繁体   English

与联接表的多对多关系

[英]Many to Many relation with join table

I have 2 models with a many-to-many relationship, event and category . 我有2个具有多对多关系, eventcategory I am trying to put together a query which let's me get the events by the category name. 我正在尝试汇总一个查询,让我通过类别名称获取事件。

I have the following tables: 我有以下表格:

category 类别

id | name

event 事件

id | name

event_categories_join event_categories_join

category_id | event_id

I've successfully gotten the events from the category id by inner joining the pivot table. 通过内部连接数据透视表,我已经成功地从类别ID中获取了事件。

SELECT * FROM event
INNER JOIN event_categories_join
ON event.id = event_categories_join.event_id
WHERE event_categories_join.category_id = 5

How do I do this by the name instead of the id? 我该如何使用名称而不是ID?


edit : 编辑

I three categories, Concert, Easter and Talks. 我分为三个类别,音​​乐会,复活节和演讲。 I also an event, London Grammar which belongs to the categories Concert and Easter. 我也是一个活动,伦敦语法,属于音乐会和复活节类别。 Now I want to write a query where I provide the name of the category, and get the belonging events - in this case Concert. 现在,我想编写一个查询,在其中提供类别名称并获取所属事件-在本例中为Concert。

You'll need another join. 您将需要另一个加入。 Try something like 尝试类似

SELECT * FROM event
INNER JOIN event_categories_join ON event.id = event_categories_join.event_id
INNER JOIN category ON category.id = event_categories_join.category_id
WHERE category.name = 'my_category';

As a side note: You should reconsider renaming event_categories_join to just event_categories . 附带说明:您应该重新考虑将event_categories_join重命名为event_categories Or maybe event_categories_mapping . event_categories_mapping This is most probably more true to the domain in question, while the join naming is to tightly coupled with the fact we're dealing with a relational database. 对于所涉及的域,这更可能是正确的,而联接的命名则与我们正在处理关系数据库的事实紧密结合。

SELECT temp.* FROM (
  SELECT event.id as eventid,event.name as eventName ,event_categories_join.* FROM event AS event 
INNER JOIN event_categories_join
ON event.eventid= event_categories_join.event_id 
) AS temp 
INNER JOIN category AS category ON 
category.id =temp.category_id
WHERE category.name = 'Maeh'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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