別名 "through を介した多対多"
through を介した多対多の関連付けは、多対多の関連付けと同じように動作しますが、through を介した多対多の関連付けでは、結合テーブルが自動的に作成される点が異なります。through を介した多対多の関連付けでは、結合する2つのモデルに対応する2つのフィールドを含むモデルを定義します。関連付けを定義する際には、自動結合テーブルの代わりにモデルを使用する必要があることを示すために、through
キーを追加します。
// myApp/api/models/User.js
module.exports = {
attributes: {
name: {
type: 'string'
},
pets:{
collection: 'pet',
via: 'owner',
through: 'petuser'
}
}
}
// myApp/api/models/Pet.js
module.exports = {
attributes: {
name: {
type: 'string'
},
color: {
type: 'string'
},
owners:{
collection: 'user',
via: 'pet',
through: 'petuser'
}
}
}
// myApp/api/models/PetUser.js
module.exports = {
attributes: {
owner:{
model:'user'
},
pet: {
model: 'pet'
}
}
}
PetUser
モデルを使用することで、通常の多対多関連付けの場合と同様に、User
モデルとPet
モデルの両方で.populate()
を使用できます。
現在、
through
テーブルに追加情報を追加したい場合、.populate
を呼び出すときには利用できません。これを行うには、through
モデルを手動でクエリする必要があります。