又稱「has one」
一對一關聯表示一個模型只能與另一個模型關聯。為了讓模型知道它與哪個其他模型關聯,其中一個記錄上必須包含外鍵,並在其上加上 unique
資料庫約束。
目前在 Waterline 中有兩種處理此關聯的方法。
在這個範例中,我們將 Pet
與 User
關聯起來。User
只能有一個 Pet
,而 Pet
只能有一個 User
。然而,為了在此範例中從雙方查詢,我們必須在 User
模型中新增 collection
屬性。這允許我們同時呼叫 User.find().populate('pet')
和 Pet.find().populate('owner')
。
這兩個模型將透過更新 Pet
模型的 owner
屬性來保持同步。新增 unique
屬性可確保每個 owner
在資料庫中只存在一個值。缺點是當從 User
端填充時,您總是會得到一個陣列。
// myApp/api/models/Pet.js
module.exports = {
attributes: {
name: {
type: 'string'
},
color: {
type: 'string'
},
owner:{
model:'user',
unique: true
}
}
}
// myApp/api/models/User.js
module.exports = {
attributes: {
name: {
type: 'string'
},
age: {
type: 'number'
},
pet: {
collection:'pet',
via: 'owner'
}
}
}
在這個範例中,我們將 Pet
與 User
關聯起來。User
只能有一個 Pet
,而 Pet
只能有一個 User
。然而,為了從雙方查詢,在 User
模型中新增了一個 model
屬性。這允許我們同時呼叫 User.find().populate('pet')
和 Pet.find().populate('owner')
。
請注意,這兩個模型不會保持同步,因此當更新其中一方時,您必須記得同時更新另一方。
// myApp/api/models/Pet.js
module.exports = {
attributes: {
name: {
type: 'string'
},
color: {
type: 'string'
},
owner:{
model:'user'
}
}
}
// myApp/api/models/User.js
module.exports = {
attributes: {
name: {
type: 'string'
},
age: {
type: 'number'
},
pet: {
model:'pet'
}
}
}