gpt4 book ai didi

mysql - 如何更新和附加值到多对多 Sequelize 实现

转载 作者:行者123 更新时间:2023-12-03 22:30:44 25 4
gpt4 key购买 nike

我有这 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 实现。例如,在我的公司 Controller 中,要获取公司,我会执行以下操作:
    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);
});
}
我该怎么做:
  • 将用户添加到公司?
  • 向用户添加公司?

  • 谢谢

    最佳答案

    sequelize 在模型上设置特殊的 methods/mixins 以帮助您处理创建的模型的副本

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

    await account.setCompanies(arrayOfCompanies);

    关于mysql - 如何更新和附加值到多对多 Sequelize 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67223101/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com