首页 > 解决方案 > 在不同模型上带有续集的生命周期钩子

问题描述

我一直在寻找这个,但我找不到我要找的东西。

基本上我有两个模型。

“X”和“Y”

在 Y 的生命周期事件(它定义了 X 的 belongsTo)上,我应该更新(递增)X 的值。稍后我会用代码来说明,但这是它的要点。

因此,每当我创建一个 Y 条目时,X 中的一个值必须增加 1。

对 sequelize 生成的 Index.js 函数使用 require 似乎没有做任何事情,我不想给我的主 routes.js 文件增加更多的复杂性。

这是“X”型号代码(命名为用户):

const bcrypt = require("bcrypt");
module.exports = (sequelize, DataTypes) => {
    const user = sequelize.define('user', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            unique: true,
            autoIncrement: true,
            required: true
        },
        username: {
            type: DataTypes.STRING,
            unique: true,
            required: true,
            validate: {
                len: [4, 32]
            }
        },
        password: {
            type: DataTypes.STRING,
            required: true,
            protect: true,
            validate: {
                len: [4, 32]
            }

        },
        likedByCount: {
            type: DataTypes.INTEGER,
            defaultValue: 0
        },
        user_likes:{
            type: DataTypes.INTEGER,
            defaultValue:0
        }
    });
    user.associate = function (models) {
        models.user.hasMany(models.like, {
            onDelete: 'cascade'
        });
    };
    user.beforeCreate((user) => {
        return bcrypt.hash(user.password, 10).then(hashedPw => {
            console.log(user.password + " hash " + hashedPw);
            user.password = hashedPw;
        });
    });
    user.beforeUpdate((user) => {
        return bcrypt.hash(user.password, 10).then(hashedPw => {
            console.log(user.password + " hash " + hashedPw);
            user.password = hashedPw;
        });

    });

    return user;


};

这是“Y”模型定义:

    const moduleFile = require("./index.js");
module.exports = (sequelize, DataTypes) => {
    sequelize
        .sync()
        .then(function (err) {
            console.log('Sync successful');
        }, function (err) {
            console.log('An error occurred while creating the table:', err);
        });
    const like = sequelize.define('like', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            unique: true,
            autoIncrement: true,
            required: true,
        },
        target_username: {
            type: DataTypes.STRING
        },
        source_username: {
            type: DataTypes.STRING
        },
        target: {
            type: DataTypes.INTEGER
        }

    });
    //HasOne and BelongsTo insert the association key in different models from each other. 
    //HasOne inserts the association key in target model whereas BelongsTo inserts the association key in the source model.
    like.associate = function (models) {
        models.like.belongsTo(models.user, {
            foreignKey: {
                allowNull: false
            }
        });
    };
    ""
    //Update the field likedByCount of target user by +1, update the field likes of source user by 1
    like.afterCreate((like) => {

        const target_id = like.target_id;
        const source_id = like.source_id;
        moduleFile.user.findById(target_id).then(user => {
             user.increment('likedByCount', {
                by: 1
            })
        }).catch((err)=>console.log("Decrement error" + err.message));
    });


    return like;

};

我的代码显然会产生错误,因为未正确找到“moduleFiles”。但我在 router.js 中也是这样做的:

var models = require("../models/index.js");

Folder structure checks out:

/ :index.js(this just launches the server)
/models/: index.js,user.js,like.js
/routes/: routes.js(this is where the above code(var models=) is from

标签: node.jssequelize.js

解决方案


推荐阅读