我只是在多对多关系中创建 Company
和 Industry
表。
一个公司可以包含多个行业,一个行业可以包含多个国家。
在 UI 中,就像公司的多选框,我可以选择多个行业。
我在模型中做什么:
工业.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',
});
CompanyIndustryRelation.associate = function(models) {
CompanyIndustryRelation.belongsTo(models.Company, { foreignKey: 'company_id' });
CompanyIndustryRelation.belongsTo(models.Industry, { foreignKey: 'industry_id' });
};
return CompanyIndustryRelation;
};
但我在这里担心的是那些模型正在
company_industry_relation
表中创建 company_id(PK) 和industry_id(PK) 。表中也没有创建 id(PK)。
在我看来,这两列(company_id 和industry_id)应该是外键,而 id(PK) 应该与这两列不同?
任何人都可以对此有所了解吗?
提前致谢!
最佳答案
您不需要关系表中的关联......只需删除它们......设置belongsToMany的任一侧就足够了......
您在关系表中的主键是复合主键……这意味着一个公司可以属于多个行业,一个行业可能有多个公司,但您永远不能复制复合主键……
company_id industry_id
1 1
1 2
2 2
2 3
这些都是连接表中的有效记录,它们的组合构成了记录的主键......所以很明显,一旦使用了 1,1,那么你就不能也不想再次添加它 type thing ...如果您在该主键中包含了一个实际的 id 字段,那么您或在您的代码中工作的其他人可能会意外地再次添加相同的关系
关于node.js - Postgresql、Node.js ORM - 相关表中的外键和主键问题(多对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60490576/