又稱「has many through」
多對多透過關聯的行為方式與多對多關聯相同,唯一的區別在於,在多對多透過關聯中,連接表是自動建立的。在多對多透過關聯中,您需要定義一個模型,其中包含兩個欄位,分別對應於您要連接的兩個模型。在定義關聯時,您將新增 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
模型。