gpt4 book ai didi

sql - 在 Node.js sequelize 和 PostgreSQL 中使用多对多关联创建/更新

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

我只是在创建或更新一个与另一个表具有多对多关联的表,如下所示:
公司 <-> 行业 <-> 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;
};

目前我已经建立了如下所示的行业表。
enter image description here

行业阵地
行业 = [ {标签:'会计'},{标签:'计算机科学'}]

公司名称:'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

关于sql - 在 Node.js sequelize 和 PostgreSQL 中使用多对多关联创建/更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60492259/

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