2013-09-28 96 views
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 

有没有一个很好的办法做到这一点在数据映射器没有下降到基础数据集?

回答

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" 
+0

感谢其他马特:) –