【发布时间】:2020-03-02 23:15:33
【问题描述】:
我只是在多对多关系中创建 Company 和 Industry 表。
一个公司可以包含多个行业,一个行业可以包含多个国家。
在 UI 中,例如公司的多选框,我可以在其中选择多个行业。
我在模型中所做的事情:
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',
});
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) 的创建应该与这两列不同?
有人对此有什么想法吗? 提前致谢!
【问题讨论】:
标签: node.js postgresql orm sequelize.js