Creating instance with an association in Sequelize

后端 未结 8 1044
清酒与你
清酒与你 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')
    }, {});
    

提交回复
热议问题