亦稱「Has Many」
一對多關聯表示一個模型可以與多個其他模型關聯。為了建立這種關聯,會使用 collection
屬性將虛擬屬性添加到模型中。在一對多關聯中,「一」方必須具有 collection
屬性,「多」方必須包含 model
屬性。這允許「多」方知道在使用 populate
時需要取得哪些記錄。
因為您可能希望一個模型在另一個模型上有多個一對多關聯,所以在 collection
屬性上需要一個 via
鍵。這表示關聯的「一」方上的哪個 model
屬性用於填充記錄。
// myApp/api/models/User.js
// A user may have many pets
module.exports = {
attributes: {
firstName: {
type: 'string'
},
lastName: {
type: 'string'
},
// Add a reference to Pets
pets: {
collection: 'pet',
via: 'owner'
}
}
};
// myApp/api/models/Pet.js
// A pet may only belong to a single user
module.exports = {
attributes: {
breed: {
type: 'string'
},
type: {
type: 'string'
},
name: {
type: 'string'
},
// Add a reference to User
owner: {
model: 'user'
}
}
};
現在寵物和使用者彼此了解了,它們可以被關聯起來。為此,我們可以建立或更新一個寵物,並將使用者的主鍵作為 owner
值。
await Pet.create({
breed: 'labrador',
type: 'dog',
name: 'fido',
// Set the User's Primary Key to associate the Pet with the User.
owner: 123
});
現在 Pet
與 User
關聯了,可以使用 .populate()
方法來填充屬於特定使用者的所有寵物。
var users = await User.find().populate('pets');
// The users object would look something like the following
// [{
// id: 123,
// firstName: 'Foo',
// lastName: 'Bar',
// pets: [{
// id: 1,
// breed: 'labrador',
// type: 'dog',
// name: 'fido',
// user: 123
// }]
// }]