Node.JS:Sequelize关联集无法恢复偏执的记录

问题描述 投票:0回答:1

我有2个模型userstags,两个都通过另一个名为usersTags的模型关联,所有3个模型都有自定义时间戳的偏执设置。我理解关联模型将添加其他方法来处理所有关联模型的关联,所以我想为用户做一个简单的setTags调用,文档显示如果在方法的数组中不包含元素应该删除存储在数据库中的数据,否则应该创建/恢复它。

所以我尝试恢复以前删除的tag但由于某种原因它失败了。模型定义如下:

用户

module.exports = function(sequelize, DataTypes) {
    const Users = sequelize.define("users", {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        username: {
            type: DataTypes.STRING(100),
            allowNull: false,
            validate: {
                len: {
                    args: [3, 100],
                    msg: "String length is not in this range"
                }
            }
        },
        password: {
            type: DataTypes.STRING(100),
            allowNull: false,
            field: "password_hash"
        }
    }, {
        tableName: "users",
        createdAt: "create_time",
        updatedAt: "update_time",
        deletedAt: "delete_time",
        paranoid: true
    });

    Users.associate = function(models) {
        // Add this association to include tag records
        this.belongsToMany(models.tags, {
            through: {
                model: models.usersTags,
                unique: true
            },
            foreignKey: "users_id",
            constraints: false
        });
    };

    return Users;
};

标签

module.exports = function(sequelize, DataTypes) {
    const Tags = sequelize.define("tags", {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: DataTypes.STRING(45),
            allowNull: false
        }
    }, {
        tableName: "tags",
        createdAt: "create_time",
        updatedAt: "update_time",
        deletedAt: "delete_time",
        paranoid: true
    });

    Tags.associate = function(models) {
        this.belongsToMany(models.users, {
            through: {
                model: models.usersTags,
                unique: true
            },
            foreignKey: "tags_id",
            constraints: false
        });
    };

    return Tags;
};

usersTags

module.exports = function(sequelize, DataTypes) {
    const UsersTags = sequelize.define("usersTags", {
        users_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            references: {
                model: "users",
                key: "id"
            }
        },
        tags_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            references: {
                model: "tags",
                key: "id"
            }
        }
    }, {
        tableName: "users_tags",
        createdAt: "create_time",
        updatedAt: "update_time",
        deletedAt: "delete_time",
        paranoid: true,
        indexes: [
            {
                unique: true,
                fields: ["users_id", "tags_id"]
            }
        ]
    });

    return UsersTags;
};

测试

let _user;

models.users.findOne({where: {id: 100}})
    .then(user => {
        _user = user;

        return _user.setTags([1]);          // Successfully create association tag with id 1
    })
    .then(() => _user.setTags([]))   // Successfully remove all associated tags
    .then(() => _user.setTags([1])); // Should restore association tag with id 1 but fails

执行查询

app:database Executing (default): SELECT `id`, `username`, `first_name`, `last_name`, `birthday`, `description`, `location`, `email`, `type`, `image_path` FROM `users` AS `users` WHERE ((`users`.`delete_time` > '2018-08-28 19:40:15' OR `users`.`delete_time` IS NULL) AND `users`.`id` = 100); +0ms
app:database Executing (default): SELECT `users_id`, `tags_id`, `create_time`, `update_time`, `delete_time` FROM `users_tags` AS `usersTags` WHERE ((`usersTags`.`delete_time` > '2018-08-28 19:40:15' OR `usersTags`.`delete_time` IS NULL) AND `usersTags`.`users_id` = 100); +6ms
app:database Executing (default): INSERT INTO `users_tags` (`users_id`,`tags_id`,`create_time`,`update_time`) VALUES (100,1,'2018-08-28 19:40:15','2018-08-28 19:40:15'); +7ms

由于某种原因,标签搜索查询无法检索包含delete_time集的标签,因此最后一个查询是insert而不是update,我知道解决方法是将paranoid设置为false但我必须跟踪所有活动,我知道另一个解决方法是创建一个自定义模型方法来处理这个,但我仍然想知道是否有办法实现这一点,而无需创建额外的自定义方法

node.js sequelize.js
1个回答
0
投票

您的代码不是正确的异步顺序,因此您的_user全局变量未启动,我认为这是正确的顺序:

let _user;

models.users.findOne({where: {id: 100}})
.then(user => {
    _user = user;
    _user.setTags([]).then(()=>{
        _user.setTags([1])
    })
})
© www.soinside.com 2019 - 2024. All rights reserved.