2

I am working with sequelize.js, Where I have a table (say User) with different string fields and a many-to-many relation with another table (say Nationality).

I am trying to insert a new row of User with all the sub-element and the nationality, in one single instruction. Now I am doing like this:

models.Nation.create({codice:"IT",name:"Italia"}).then(function(italy){
      models.User.create({username:"local_u",nation:italy}).then(function(){

     });
});

If I look at the database, at the newly created User row: the fieldNationId` is not set.

I know I can use the function setNation of sequelize, but I wonder if I can do it within one single User.create.

3
  • btw you need to return the second one. return models.User.create... Commented Dec 26, 2015 at 17:28
  • huh, interesting! Is it necessary? or just philosophically required? because things are working without the return Commented Dec 26, 2015 at 17:42
  • it's necessary, so no errors would go undetected. currently the Nation.create promise won't catch errors in User.create. Bluebird should warn you about this already. Commented Dec 26, 2015 at 17:43

1 Answer 1

1

Yes you can create the user entity with nation in one step using include. Something like this (code not tested):

models.Nation.create({ codice: "IT", name: "Italia" }).then(function (italy) {
    models.User.create({
        username: "local_u",
        nation: italy

    }, {
            include: [models.nation]
        }
    ).then(function () {/*Do Something*/});
});

It's an old question but hopefully will help someone.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.