我真的不明白为什么会有关联。我有一个包含两个表的MariaDB数据库:公社和code_postals。
code_commune是city_code和code_postal postal_code。因此,一个城市可以有多个postal_code,多个城市可以共享同一个postal_code。
我的SLQ请求一定是这样的:
SELECT * FROM code_postals P INNER JOIN communes C ON P.code_commune=C.code_commune;
在我的TypeScript数据存储库类中,我有以下代码:
const Communes = await this.db.define('commune', {
code_commune: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
libelle_commune: {
type: DataTypes.STRING,
allowNull: false
}
});
const Postal = await this.db.define('code_postal', {
code_commune: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
code_postal: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
}
});
// Define the relationship between the both tables
Postal.hasOne(Communes,{foreignKey: 'code_commune'});
Communes.belongsTo(Postal);
return await Postal.findAll({include: Communes}).then((communes:any)=>{
return communes;
}).catch((e:any)=>{console.error(e);return false;});
我不太理解文档、hasOne、belongsTo、belongsToMany等方法之间的区别,也不知道如何提出这个关联请求。
我是普利兹
发布于 2021-10-01 16:49:19
如果一个城市可以有多个邮政编码,同时一个特定的邮政编码对几个城市来说是相同的,那么城市和邮政编码之间就有M:N的关系,需要像CommunesPostalCodes
这样的第三个连接表。
const Communes = await this.db.define('commune', {
code_commune: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
libelle_commune: {
type: DataTypes.STRING,
allowNull: false
}
});
const Postal = await this.db.define('code_postal', {
code_postal: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
}
});
const CommunePostal = await this.db.define('commune_postal', {
id: {
type: DataTypes.SERIAL,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
code_commune: {
type: DataTypes.INTEGER,
allowNull: false
},
code_postal: {
type: DataTypes.INTEGER,
allowNull: false
}
});
// Define the relationship between the both tables
Postal.belongsToMany(Communes,{ through: CommunePostal, foreignKey: 'code_postal', otherKey: 'code_commune'});
Communes.belongsToMany(Postal,{ through: CommunePostal, foreignKey: 'code_commune', otherKey: 'code_postal'});
https://stackoverflow.com/questions/69394717
复制相似问题