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

前端 未结 1 1853
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 07:33

So the reason why im confused, because I am a PHP developer and used Laravel and FuelPHP alot

What i dont really understand is the association it self.

What

相关标签:
1条回答
  • 2021-01-03 07:59

    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.

    0 讨论(0)
提交回复
热议问题