简体   繁体   中英

Many-to-Many: sequelize doesn't create methods

Consider two models User and Project with the relation Many-To-Many.

When I try this: db.User.getProjects() I get an error

TypeError: Object [object Object] has no method 'getProjects()'

I've read in the docs this method should be generated automatically
So why I get this error?

Source Code:

project.js

module.exports = function(sequelize, DataTypes) {
    var Project = sequelize.define('Project', {
        name: DataTypes.STRING
    }, {
        classMethods: {
            associate: function(models) {
                Project.hasMany(models.User);
            }
        }
    })

    return Project
}

user.js

module.exports = function(sequelize, DataTypes) {
    var User = sequelize.define('User', {}, {
        classMethods: {
            associate: function(models) {
                User.hasMany(models.Project),
                User.belongsTo(models.Boss, {
                    foreignKey: 'user_id'
                })
            }
        }
    })

    return User
}

That is because db.User is the model, and not the instance.

the getAccessor() methods are invoked upon instances. You should do something like:

db.User
    .find( {where: {user_id: user_id}} )
    .then(function(user) {
        return user.getProjects();
    })
    .then(function(projects) {
        //do something with your projects DAO
    })
    .catch(function(err) {});

It is the instance, or the DAO that is returned from your first db.User.find that has the methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM