2013-09-28 98 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

感謝其他馬特:) –