mysql - 如何更新和附加一个值到多对多的续集实现
问题描述
我有这 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);
});
}
我该怎么做:
- 将用户添加到公司?
- 将公司添加到用户?
谢谢
解决方案
sequelize 在模型上设置特殊的方法/mixin,帮助你处理你创建的模型的对应部分
const account = await Account.create({ myAccountProps });
await account.setCompanies(arrayOfCompanies);
推荐阅读
- css - Angular 9 在 css 中使用材质图标作为列表
- python - 如何使用 IPython --pdb 调试 Python 脚本?
- ajax - Prestashop 1.7.4.2 - 添加到购物车 ajax 非常慢(TTFB 3 秒)
- c++ - 如何以多线程方式编码位图块?
- elasticsearch - 如何使用 Kibana“脚本字段”查找重复项?
- docker - 无法连接到 Heroku 上的 dockerised redis
- visual-studio-2019 - System.Web.Http问题影响通信
- javascript - React 在组件之间共享数据而无需重新加载组件
- sql - SQL Server 查询日期和金额
- excel - 如何使用自定义扩展名将 Excel 工作表另存为 csv?