【问题标题】:Rails has_and_belongs_to_many join across 3 tablesRails has_and_belongs_to_many 跨 3 个表连接
【发布时间】:2010-10-21 17:54:37
【问题描述】:

我有三个模型:listing、category 和 site。列表和站点之间存在多对多关系,列表和类别之间存在多对多关系。因此,一个列表属于一个或多个站点和一个或多个类别(一个列表可以出现在多个站点和多个类别中)。

给定一个站点 ID 和一个类别 ID,我想要一组所有列表。我了解如何从站点 id (listings = site.listings) 中获取列表以及如何从类别 id (listings = category.listings) 中获取列表,但是如何从列表中获取列表集的三重连接站点 ID 和类别 ID?

sql 看起来像(sit_id 和 cat_id 是输入): select l.name from Listings l, categories_listings cl, listings_sites, ls where cl.category_id = cat_id 和 ls.site_id = sit_id 和 cl.listing_id = l.id 和 ls.listing_id = l.id

提前致谢

【问题讨论】:

    标签: ruby-on-rails join many-to-many


    【解决方案1】:

    您可能需要做一个 has_many :through 并通过将 belongs_to 指定给父表来定义模型中的连接表。

    课堂作业:作业 结尾 类项目:作业 结尾

    这个 [链接][1] 也可能有帮助。

    干杯,祝你好运。

    [1]:帮助? Rails: has_many :through or has_many_and_belongs_to?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-21
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2011-09-30
      相关资源
      最近更新 更多