外鍵我一直在尋找通過這個:引用與DataMapper的
http://datamapper.org/docs/find
但一直沒能閃耀正是我要找的,雖然我知道這是很簡單的。
我有兩個表,掃描和車站,與相關領域:
STATIONS - id (primary key), name
SCANS - id (primary key), item_id, in_station, out_station
凡in_station
和out_station
外鍵的id
字段中stations
表。
我有一個Scan
對象
class Scan
include DataMapper::Resource
property :id, Integer, :key => true
property :item_id, Integer
property :in_station, Integer
property :out_station, Integer
end
所以現在,我可以做Scan.all(:item_id => @barcode)
工作再上一個特定項目所有的掃描,我已經得到了in_station
ID和out_station
ID。不過,取代名稱的最佳方式是什麼?我認爲這比每次掃描Station.get(:id=> scan.in_station)
都要容易得多。
這是很容易使用SQL足夠了,但我怎麼可以改變掃描/站要麼得到的名字,或是有這是一個站對象的屬性,所以我可以做類似scan.station.name?
編輯:
我幾乎得到了這個工作。我有一個站類:
class Station
include DataMapper::Resource
property :id, Integer, :key => true
property :name, String
end
和我擺脫property :in_station
和Scan
property :out_station
,取而代之的是:
belongs_to :in_station, :model => 'Station', :child_key => 'id'
belongs_to :out_station, :model => 'Station', :child_key => 'id'
這一點我想/希望的說:「有一個字段名爲in_station這是一個將外鍵插入到電臺表格中,並將其中一個叫做out_station,它們是相同的「。事實上,in_station和out_station現在是Station的實例,但是,它們是對象。儘管in_station和out_station是不同的值,但我在每個掃描中都會得到相同的對象。我做錯了什麼,我怎麼能指出in_station和out_station都是對站的引用,但是當他們的id不同時,我期望不同的對象。
看看在數據庫中搜索表創建的領域。就像我下面所說的,儘管名稱'child_key'暗示了另外一種情況,您需要使用像下面所示的名稱。 你的'belongs_to'行說的是「掃描屬於一個名爲'in_station'的關聯站,並且將加載一個名爲'id'的掃描屬性的'id'的站。這不是你想要的。你想要「掃描屬於一個名爲'in_station'的關聯站,並將加載一個名爲'in_station_id'的Scan屬性的'id'。 – Larsenal 2011-03-31 20:00:43