编辑页面

.populate()

修改一个 查询实例,以便在执行时,为指定的集合填充子记录,可以选择通过subcriteria进行过滤。只要每次调用都是针对不同的关联,就可以在同一个查询上多次调用 populate。

.populate(association, subcriteria)

用法

#
参数 类型 详情
1 关联 String 要填充的关联的名称。例如:snacks
2 子条件 Dictionary? 可选。在填充两个模型之间位于同一数据库中的集合关联时,可以将 Waterline 标准 作为 populate 的第二个参数指定。这将用于过滤、排序和限制与每个主记录关联的关联记录(例如 snacks)的数组。

重要: 基本联接 polyfill(跨数据存储填充,或在配置的适配器未提供.join()实现的模型之间填充)和.populate()的 subcriteria 参数在 Sails 中都单独完全受支持。但是,在使用联接 polyfill 的同时使用.populate()的 subcriteria 参数属于实验性功能。这意味着,如果关联跨越多个数据存储或其数据存储的配置适配器不支持物理层联接,则不应依赖于.populate()的 subcriteria 参数。如果您在生产环境中尝试这样做,您将看到一条警告消息记录到控制台。SQL 适配器(例如 sails-postgresqlsails-mysql)支持原生联接,并且可以使用 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
]

是否缺少某些内容?

如果您发现我们遗漏了某些内容或可以改进的地方,请按照 此链接 并向 Sails 代码库提交拉取请求。一旦我们合并它,更改将在网站下次部署时反映出来。

参考

参考