首页 > 解决方案 > 如何更新和附加一个值到多对多的续集实现

问题描述

我有这 2 个模型描述了我需要执行 api 操作的 2 个表:

// USER MODEL
'use strict';
const {
    Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
    class User extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            // define association here
            User.belongsToMany(models.Company, {
                through: 'UserCompany',
                foreignKey: 'id',
            })
        }
    };
    User.init({
        firstname: DataTypes.STRING,
        lastname: DataTypes.STRING,
        phone: DataTypes.STRING
    }, {
        sequelize,
        modelName: 'User',
    });
    return User;
};

// COMPANY MODEL
'use strict';
const {
    Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
    class Company extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            // define association here
            Company.belongsToMany(models.User, {
                through: 'UserCompany',
                foreignKey: 'id',
            })
        }
    };
    Company.init({
        company_name: DataTypes.STRING
    }, {
        sequelize,
        modelName: 'Company',
    });
    return Company;
};

我希望能够将用户添加到公司,并将公司添加到用户。因此这里是多对多 /belongsToMany实现。例如,在我的公司控制器中,要获取公司,我会:

    getById(req, res) {
        return Company
            .findByPk(req.params.id, {
                include: [{
                    model: User,
                    as: 'users'
                }],
            })
            .then((company) => {
                if (!company) {
                    return res.status(404).send({
                        message: 'Company Not Found',
                    });
                }
                return res.status(200).send(user);
            })
            .catch((error) => {
                console.log(error);
                res.status(400).send(error);
            });
    }

我该怎么做:

谢谢

标签: mysqlnode.jsdatabasesequelize.js

解决方案


sequelize 在模型上设置特殊的方法/mixin,帮助你处理你创建的模型的对应部分

const account = await Account.create({ myAccountProps });

await account.setCompanies(arrayOfCompanies);

推荐阅读