【问题标题】:Should one-to-one associations populate both sides?一对一的关联是否应该填充双方?
【发布时间】:2015-09-14 00:21:09
【问题描述】:

我有两个模型(用户和代理)。然后我创建一个用户和一个代理。我希望在为 /user 和 /agent 使用蓝图路由时看到关联。我只看到用户模型通过 /agent 蓝图与代理相关联。 /user 蓝图与代理没有任何引用/关联。

当我尝试使用以下命令通过用户 ID 访问代理时,问题就出现了:

User.findOne(req.body.userId).populate('agent').exec(function(err, agent)

“代理”其实是用户信息……不是代理。

这是我的模型:

用户:

attributes: {
  agent: {
    model: 'agent',
    via: 'owner'
  }
}

代理:

attributes: {
  owner: {
    model: 'user'
  }
}

感谢阅读!

【问题讨论】:

    标签: node.js model sails.js waterline


    【解决方案1】:

    Sails 不完全支持一对一的模型关联——你必须在两边都设置“外键”。请参阅https://stackoverflow.com/a/27752329/345484 了解更多信息。我很想把这个问题作为那个问题的副本来结束,但设置略有不同。

    【讨论】:

      【解决方案2】:

      你对populate的理解是错误的。 populate() 不会用新信息替换上次通话。它从模型中获取属性(您在 populate('attribute') 中指定)并将模型中该属性的 id 替换为通过其 id 查找的另一个模型信息。

      让我们深入示例。

      您有 UserAgent 模型。

      // api/models/User.js
      module.exports = {
        attributes: {
          agent: {
            model: 'Agent',
            via: 'owner'
          }
        }
      };
      
      // api/models/Agent.js
      module.exports = {
        attributes: {
          owner: {
            model: 'User',
            via: 'agent'
          }
        }
      };
      

      您正在致电User.findOne(userId).populate('agent').exec(function(err, user) {},并且预计只会收到agent,据我所知。错误的。它返回User 模型和Agent 模型作为User 模型的属性。

      // api/controllers/AnyController.js
      module.exports = {
        index: function(req, res) {
          User
            .findOne(req.param('userId'))
            .populate('agent')
            .then(function(user) {
              console.log(user); // User information
              console.log(user.agent); // Agent information for that user
              return user;
            })
            .then(res.ok)
            .catch(res.negotiate);
        }
      };
      

      你可以在这里阅读更多关于人口的信息 - http://mongoosejs.com/docs/populate.html

      【讨论】:

      • 我不认为这是 OP 所面临的问题——这听起来更像是对 Sails 中一对一关联支持的误解。
      • @sgress454 我不知道。每次我建立一对一关联时,一切都会按预期工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      相关资源
      最近更新 更多