【问题标题】:Query for associated Sequel models based on attributes in join table根据连接表中的属性查询关联的 Sequel 模型
【发布时间】:2018-05-25 17:27:54
【问题描述】:

鉴于Sequel::Model 商品和商店,通过Listings 加入,我想根据列表的属性找到Items 及其关联的Stores

DB.create_table? :items
  primary_key :id
end

DB.create_table? :stores
  primary_key :id
end

DB.create_table? :listings
  foreign_key :store_id
  foreign_key :item_id
  TrueClass :active, null: true
  String :name
end

class Item < Sequel::Model
  many_to_many :stores, join_table: :listings
end

class Store < Sequel::Model
  many_to_many :items, join_table: :listings
end

class Listing < Sequel::Model
end

我可以使用.association_join.where 子句来执行此操作(如下所示),但是(A)我不确定这是否正确(B)它会产生一个带有来自两者的道具的结果连接表和 (C) 对结果 Item 调用 #stores 会导致另一个查询。

Item.association_join(:stores).where(active: true, name: 'Sears').eager(:stores).first()

我的最终目标是一个Items 的数据集,它将热切地加载#stores

这样做的最佳方法是什么?谢谢!

【问题讨论】:

    标签: ruby postgresql sequel


    【解决方案1】:

    我发现的另一种方法是:

    Listing.eager(item: :stores).where(active: true).all
    

    这会预先产生三个查询,但我感兴趣的整个关联链都已加载。然后我从列表数组中收集项目。

    也不确定这是否是正确的方式。

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 2012-01-15
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      相关资源
      最近更新 更多