【问题标题】:What is populate in SailsJs?SailsJs 中填充了什么?
【发布时间】:2014-12-09 12:20:39
【问题描述】:

我最近开始在sailsJs上进行开发,但不了解其中的微妙之处 请向我解释 SailsJs 中填充了什么以及谁能做简单的例子 提前致谢 ? 是什么?

User.find({ name: 'foo' })
.populate('pets', { name: 'fluffy' })
.exec(function(err, users) {
  if(err) return res.serverError(err);
  res.json(users);
});

【问题讨论】:

  • @LeonidBeschastny Sails 使用水线作为默认 ORM。而且 waterline 也支持关联,虽然这个功能在 mongoose 中已经存在很长时间了。
  • 如果以下答案满足您的问题,那么建议您将答案标记为已接受,这也是一种很好的做法。
  • read the documentation也是很好的做法。

标签: node.js sails.js waterline


【解决方案1】:

populate 用于关联。当你的模型是这样的:

// User.js
module.exports = {
  attributes: {

    name: {
      type: "string"
    },

    pet: {
      model: "pet"
    }

  }
}

这里用户集合的pet属性是对pet表的引用。在用户表中,它将仅存储宠物的 id 列。但是,当您在查找时执行填充时,它将获取宠物条目的整个记录​​并在此处显示。这只是一对一的关联。您可以拥有多对一关联以及多对多关联。有关详细信息,请参阅此documentation

【讨论】:

    【解决方案2】:

    sailsjs 项目使用wateline ORM。你可以看到文件。如果你想使用'populate()',你需要在模型中定义关联。

    .populate()

    populate 与关联一起使用以包含模型定义中指定的任何相关值。如果集合属性在多对多、一对多或多对多关联中定义,则填充选项也接受完整的条件对象。这允许您过滤关联并运行限制并跳过结果。

    作为你的例子,你需要这样做:

    用户.js

    // A user may have many pets
    var User = Waterline.Collection.extend({
    
      identity: 'user',
      connection: 'local-postgresql',
    
      attributes: {
        firstName: 'string',
        lastName: 'string',
    
        // Add a reference to Pets
        pets: {
          collection: 'pet',
          via: 'owner'
        }
      }
    });

    宠物.js

    // A pet may only belong to a single user
    var Pet = Waterline.Collection.extend({
    
      identity: 'pet',
      connection: 'local-postgresql',
    
      attributes: {
        breed: 'string',
        type: 'string',
        name: 'string',
    
        // Add a reference to User
        owner: {
          model: 'user'
        }
      }
    });

    你可以准备好文档,你可以很容易地使用它

    【讨论】:

      【解决方案3】:

      恢复 .populate() (由 waterline 使用)有点类似于 SQL 使用的 join

      .populate() 允许您连接数据库中的表。 链接标识符将在您的模型中定义。

      换句话说,要将用户(在“用户”表中)与狗(在“狗”表中)关联,您可以使用填充。

      继续你的例子:

      您正在寻找用户 => User.find ({name: my_user})
      您正在寻找名为“fluffy”的狗 => {name: 'fluffy'}
      您正在寻找与您的用户(属于)相关联的狗“蓬松”=> 填充(“宠物”)

      哪个给:

      User.find({ name: 'foo' })
      .populate('pets', { name: 'fluffy' })
      .exec(function(err, users) {
       if(err) return res.serverError(err);
       res.json(users);
      }
      

      这个关联(“pets”),你在你的模型“User”和“Pets”中定义它,就像上面的例子一样。

      【讨论】:

        【解决方案4】:

        Populate 就是显示重新释放它的 (id) 的内容

        "abc": [{
            type: ObjectId,
            ref: "xyz"
        }],
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多