I am confused with Sails.js waterline one-to-one association logic

风格不统一 提交于 2019-11-30 15:39:19
sgress454

It is a known issue that Sails doesn't fully support one-to-one associations; you have to set the foreign key on whichever side you want to be able to populate from. That is, if you want to have User #1 linked to Profile #1 and be able to do User.find(1).populate('profile'), you would set the profile attribute of User #1, but that doesn't automatically mean that doing Profile.find(1).populate('user') will work. This is as opposed to many-to-many relationships in Sails, where adding the link on one side is sufficient. That's because to-many relationships use a join table, whereas to-one relationships do not.

The reason this hasn't been a priority in Sails is that one-to-one relationships are usually not really useful. Unless you have a really compelling reason for not doing so, you're better off just merging the two models into one.

In any case, if it's something you really need, you can use the .afterCreate lifecycle callback to ensure a bi-directional link, for example in User.js:

module.exports = {

  attributes: {...},

  afterCreate: function(values, cb) {

    // If a profile ID was specified, or a profile was created 
    // along with the user...
    if (values.profile) {
      // Update the profile in question with the user's ID
      return Profile.update({id: values.profile}, {user: values.id}).exec(cb);
    }

    // Otherwise just return
    return cb();
  }
};

You could add a similar .afterCreate() to Profile.js to handle updating the affected user when a profile was created.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!