1

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

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

有没有一种很好的方法可以在数据映射器中执行此操作而无需放入底层数据集?

4

1 回答 1

1

You need to specify that a Family has several Persons. See the documentation on has n and belongs_to.

class Family
  include DataMapper::Resource

  property :id,   Serial
  property :nice, Boolean

  # add this:
  has n, :people
end

Then you can use this:

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

The SQL generated is actually a subquery rather than a join:

 SELECT "id", "family_id" FROM "people" WHERE "family_id" IN (SELECT "id" FROM "families" WHERE "nice" = 't') ORDER BY "id"
于 2013-09-28T12:42:49.580 回答