.populate()
修改查詢實例,使其在執行時,會為指定的集合填充子記錄,並可選擇性地依 subcriteria
篩選。populate
可以對同一個查詢呼叫多次,只要每次呼叫針對不同的關聯即可。
.populate(association, subcriteria)
參數 | 類型 | 詳細資訊 | |
---|---|---|---|
1 | association (關聯) | 要填充的關聯名稱。例如:snacks 。 |
|
2 | subcriteria (子條件) | 選填。當填充位於同一個資料庫中兩個模型之間的 collection 關聯時,可以將 Waterline 條件 指定為 populate 的第二個參數。這將用於篩選、排序和限制與每個主要記錄相關聯的關聯記錄陣列 (例如 snacks)。 |
重要: 基本的 join polyfill (跨資料儲存區填充,或在配置的 adapter 不提供
.join()
實作的模型之間填充) 和.populate()
的 subcriteria 參數都已在 Sails 中獲得個別完整支援。然而,同時使用.populate()
的 subcriteria 參數和 join polyfill 仍處於實驗階段。這表示,如果關聯跨越多個資料儲存區,或其資料儲存區的配置 adapter 不支援實體層 join,則您不應依賴.populate()
的 subcriteria 參數。如果您在生產環境中嘗試這樣做,您將會在主控台中看到警告記錄。SQL adapter,例如 sails-postgresql 和 sails-mysql 支援原生 join,應該可以安全地使用 subcriteria 參數。
注意: 如果您使用
schema: false
,則只會填充已定義的屬性。
以下範例會在資料庫中尋找任何名為 Finn 的使用者,並為每位使用者填充其父親
var usersNamedFinn = await User.find({name:'Finn'}).populate('dad');
sails.log('Wow, there are %d users named Finn.', usersNamedFinn.length);
sails.log('Check it out, some of them probably have a dad named Joshua or Martin:', usersNamedFinn);
return res.json(usersNamedFinn);
這可能會產生
[
{
id: 7392,
age: 13,
name: 'Finn',
createdAt: 1451088000000,
updatedAt: 1545782400000,
dad: {
id: 108,
age: 47,
name: 'Joshua',
createdAt: 1072396800000,
updatedAt: 1356480000000,
dad: null
}
},
// ...more users
]
此範例使用選填的 subcriteria 參數。
以下範例會在資料庫中尋找任何名為 Finn 的使用者,並為每位使用者填充其三把最潮的紫色劍,依潮度降序排列
// Warning: This is only safe to use on large datasets if both models are in the same database,
// and the adapter supports optimized populates.
// (e.g. cannot do this with the `User` model in PostgreSQL and the `Sword` model in MongoDB)
var usersNamedFinn = await User.find({ name:'Finn' })
.populate('currentSwords', {
where: {
color: 'purple'
},
limit: 3,
sort: 'hipness DESC'
});
// Note that Finns without any swords are still included -- their `currentSwords` arrays will just be empty.
sails.log('Wow, there are %d users named Finn.', usersNamedFinn.length);
sails.log('Check it out, some of them probably have non-empty arrays of purple swords:', usersNamedFinn);
return res.json(usersNamedFinn);
這可能會產生
[
{
id: 7392,
age: 13,
name: 'Finn',
createdAt: 1451088000000,
updatedAt: 1545782400000,
dad: 108,//<< not populated
swords: [//<< populated
{
id: 9,
title: 'Grape Soda Sword',
color: 'purple',
createdAt: 1540944000000,
updatedAt: 1540944000000
},
// ...more swords
]
},
// ...more users
]