Creating instance with an association in Sequelize

后端 未结 8 1042
清酒与你
清酒与你 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:34

    First of all you need to setup the relations in both ways, like this:

    // Set up the models
    var User = sequelize.define('User', {});
    var Login = sequelize.define('Login', {});
    
    // Set the correct associations
    User.hasMany(Login, {})
    Login.belongsTo(User, {});
    

    Then, you need to properly get the instances returned by the promises:

    // Create the instances
    User.create({}).then(function(newUser) {
        // now you can use newUser acessors to create the login
        return newUser.createLogin({});
    ).then(function(newLogin){
        // newLogin
    }).catch(function(error){
        // error
    });
    

提交回复
热议问题