数据映射器中的外部引用

时间:2013-09-28 11:49:45

标签: ruby-datamapper

假设我有两个这样的数据映射器类:

class Family
   include DataMapper::Resource

   property :id,   Serial
   property :nice, Boolean
end

Class Person
   include DataMapper::Resource

   property :id, Serial

   belongs_to :family
end

如果我想让属于某个家庭的所有人family,我可以使用此功能:

people=Person.all(:family=>family)

但是如果我想让所有属于nice属性的家庭成员呢?在SQL中,我可以做到

SELECT * FROM persons, families WHERE persons.family_id=families.id AND families.nice

有没有一种很好的方法可以在数据映射器中执行此操作而不必删除到基础数据集?

1 个答案:

答案 0 :(得分:1)

您需要指定Family有多个Person s。请参阅documentation on has n and belongs_to

class Family
  include DataMapper::Resource

  property :id,   Serial
  property :nice, Boolean

  # add this:
  has n, :people
end

然后你可以使用它:

Family.all(:nice => true).people

生成的SQL实际上是子查询而不是连接:

 SELECT "id", "family_id" FROM "people" WHERE "family_id" IN (SELECT "id" FROM "families" WHERE "nice" = 't') ORDER BY "id"