【发布时间】:2020-03-03 06:38:42
【问题描述】:
我只是在创建或更新一个与另一个表具有多对多关联的表,如下所示: 公司 行业 CompanyIndustryRelation。
Industry.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;
};
行业阵列 行业 = [ {标签:'会计'},{标签:'计算机科学'}]
公司名称:'ApolloIT'
我想使用给定的行业数组和公司名称创建新的公司记录。
提前致谢!
【问题讨论】:
-
您的问题不清楚。请更具体。如果您展示一个数据示例以及您想要实现的目标,那就更好了。与你的关系我只能看到
Company -> CompanyIndustryRelation <- Industry。不清楚您要创建或更新什么。 -
丹,感谢您的回复!刚刚更新了问题。
-
丹,我试过这样
for (const i of industry) { const industryInstance = await Industry.findOne({ industry_name: i.label }); await CompanyIndustryRelation.create({ company_id: company.id, industry_id: industryInstance.id }); }但它说错误"id" of relation "company_industry_relation" does not exist
标签: sql node.js postgresql sequelize.js