Creating instance with an association in Sequelize

后端 未结 8 1019
清酒与你
清酒与你 2021-02-02 09:09

Using Sequelize, I\'ve created two models: User and Login.

Users can have more than one Login, but a login must have exactly one user, which me

相关标签:
8条回答
  • 2021-02-02 09:40

    For those like me who were trying to create an instance of a model including another instance, like:

    var login1 = await Login.create(...);
    var user1 = await User.create({
        Login: login1
    }, {
        include: Login
    });
    

    You can't because this method is used to embed an instance (Login) which is not already existing and that will be created at the parent instance (User) creation level.

    So, if you want to embed an already existing Login in the newly created User, do instead:

    var login1 = await Login.create(...);
    var user1 = await User.create({
        loginId: login1.get('id')
    }, {});
    
    0 讨论(0)
  • 2021-02-02 09:43

    In your .then, the callback receives the model instance created by the previous call. You need to specify the argument inside the callback function.

    var user = User.create().then(function(user) {
    
      // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION
      var login = Login.create({
        userId: user.get('id')
      });
    
      return login
    
    }).then(function(login) {
        // all creation are complete. do something.
    });
    

    Also something important I would like to point out is your missing var statements! Those are important but not related to this question. See Declaring variables without var keyword

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