sql - 在 Node.js sequelize 和 PostgreSQL 中使用多对多关联创建/更新
问题描述
我只是在创建或更新与另一个表具有多对多关联的表,如下所示:Company <-> Industry <-> CompanyIndustryRelation。
工业.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Industry = sequelize.define('Industry', {
industry_name: DataTypes.STRING,
}, {
timestamps: false,
underscored: true,
tableName: 'industry',
});
Industry.associate = function(models) {
Industry.belongsToMany(models.Company, {
through: 'company_industry_relation', foreignkey: 'industry_id'
});
};
return Industry;
};
公司.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Company = sequelize.define('Company', {
company_name: DataTypes.STRING,
}, {
timestamps: false,
underscored: true,
tableName: 'company',
});
Company.associate = function(models) {
Company.belongsToMany(models.Industry, {
through: 'company_industry_relation', foreignKey: 'company_id'
});
};
return Company;
};
CompanyIndustryRelation.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const CompanyIndustryRelation = sequelize.define('CompanyIndustryRelation', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
},
}, {
timestamps: false,
underscored: true,
tableName: 'company_industry_relation',
});
return CompanyIndustryRelation;
};
行业数组行业 = [ { label: 'Accounting' }, { label: 'Computer Science' } ]
公司名称:'ApolloIT'
我想用给定的行业数组和公司名称创建一个新的公司记录。
提前致谢!
解决方案
我找到了一种使用关联创建/更新记录的简单方法。
industries: [
{ value: 'Gaming', label: 'Gaming' },
{ value: 'Computer Science', label: 'Computer Science' }
]
const company = await Company.create({
company_name: companyName,
});
const industry = await Industry.findAll({
where: { industry_name: { [Op.in]: _.map(industries, o => o.label) } }
});
await company.addIndustry(industry);
请参考这里。https://sequelize.org/master/manual/advanced-many-to-many.html
推荐阅读
- visual-studio-code - 如何摆脱 Visual Studio 代码的自动格式化?
- c# - 如何根据 C# 数据库中的数据表值在 Winforms 中生成动态按钮?
- javascript - (DOM 问题)不返回任何东西
- android - 应用程序的运行时权限
- python - 从视图 Django 中的请求函数调用函数
- javascript - How can I declare a global function to call an Angular service from the browser console?
- python - Pymel:删除空组后如何关闭 For 循环?
- angular - 使构建在生产中失败,但在开发模式下失败
- ios - 在其他网站中加载 iframe 时,cookie 禁用 ios Safari 中的错误
- java - 如何在 Android 中以编程方式更改菜单标题