別名「Has Many」
1対多の関連付けは、あるモデルが他の多くのモデルと関連付けられることを示します。この関連付けを構築するには、collection
プロパティを使用して、モデルに仮想属性を追加します。1対多の関連付けでは、「1」側はcollection
属性を持ち、「多」側はmodel
属性を持つ必要があります。これにより、「多」側はpopulate
が使用されたときに、どのレコードを取得する必要があるかを知ることができます。
モデルが別のモデルに対して複数の1対多の関連付けを持つことを望む場合があるため、collection
属性にはvia
キーが必要です。これは、関連付けの「1」側で、レコードの投入に使用される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
// }]
// }]