Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solved: How to add relationship #80

Closed
eikaramba opened this issue Nov 29, 2016 · 3 comments
Closed

Solved: How to add relationship #80

eikaramba opened this issue Nov 29, 2016 · 3 comments

Comments

@eikaramba
Copy link
Contributor

eikaramba commented Nov 29, 2016

After several days i don't know what to do anymore. My use case is simple:

After a user is created let's add a default item to his inventory (MxN relationship)

According to the sequelize docs we just call the appropiate prototype function.

Let's say we have an after hook as following:

return function(hook) {
    if(hook.result){                                        //If user creation was successful
      return hook.app.service('items').get(1).then(item=> {        //Find default item ...
        hook.result.addInventory(item);                     //and add it to the user
      });
    }
  };

FYI, this is the model relation definition(vice versa for items):

user.associate = function(models) {
    user.belongsToMany(models.items, { as:'Inventories', through: 'inventories'});
  };
@eikaramba eikaramba changed the title Cannot add relationship Solved: How to add relationship Nov 29, 2016
@eikaramba
Copy link
Contributor Author

I got it working finally! I updated my code above. Don't know why it wasn't working like that from the beginning(must have made some silly error).

@daffl
Copy link
Member

daffl commented Nov 29, 2016

You have to return the promise, otherwise the hook won't wait for it to finish (which means that if the above code works it is only by accident):

return function(hook) {
  if(hook.result) {
    return hook.app.service('items').get(1).then(item => {
      hook.result.addInventory(item);
    });
  }
};

@eikaramba
Copy link
Contributor Author

eikaramba commented Nov 29, 2016

Yes you are right, actually i also added this in my code but forgot to update the code above.

Also even hook.result.addInventory(1) will work. Sequelize supports it to add a relation just with the ID alone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants