Sequelize Association in class methods not working

穿精又带淫゛_ 提交于 2021-01-27 20:50:53

问题


I'm trying to set associations in class methods but it's not working as it should!

const User = sequelize.define('User', {
    email: DataTypes.STRING,
    password: DataTypes.STRING,
}, {
    classMethods: {
        associate: (models) => {
            User.hasMany(models.AnotherModel, {foreignKey: 'userId'});
        },
   }
});

But when i set associations outside of classMethods block it works:

User.associate = function (models) {
    User.hasMany(models.AnotherModel, {foreignKey: 'userId'});
};

why the codes inside classMethods block not working?

sequelize version: 4.2.0


回答1:


This is an expected behavior, the classmethod syntax refers to sequelize version < 4.

Since v4, sequelize has evolved more towards js class syntax and hence the change.

The upgrade manual here details more about it




回答2:


Remember when library owners would leave the old method in place for a period of time, have it report that it's deprecated, but still operate so when we revisit a three year old project, and have zero idea why bringing the code forward breaks the entire universe, we might could get some direction on a resolution? I remember those days. Heady, wonderful days, those.

We're in the middle of a large code-forward update, bringing an old application to the modern versions of Node, et al, and holy crap, everything is just flat out broken. This'll be fun.

Digging in, this is "expected behavior", but wow, what a horrible way to learn about it. :(




回答3:


with "sequelize": "5". Used this on my code to develop OSE server in Peru:

'use strict';
module.exports = (sequelize, DataTypes) => {

const UserModel = sequelize.define('user', {
    user: DataTypes.STRING,
    password: DataTypes.STRING,
    description: DataTypes.STRING
}, {});
UserModel.associate = function (models) {
    // associations can be defined here
};
UserModel['getHashName'] = () => {
    return 'UserCache';
};
UserModel['getCacheKey'] = () => {
    return 'user';
};
UserModel['getCacheValue'] = () => {
    return 'password';
};
return UserModel;
};

and well, the next call :

console.log(User.getHashName());
console.log(User.getCacheKey());
console.log(User.getCacheValue());


来源:https://stackoverflow.com/questions/44889345/sequelize-association-in-class-methods-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!