首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MariaDB关系

MariaDB关系
EN

Stack Overflow用户
提问于 2021-09-30 15:13:24
回答 1查看 67关注 0票数 0

我真的不明白为什么会有关联。我有一个包含两个表的MariaDB数据库:公社和code_postals。

数据库模式

code_commune是city_code和code_postal postal_code。因此,一个城市可以有多个postal_code,多个城市可以共享同一个postal_code。

我的SLQ请求一定是这样的:

代码语言:javascript
运行
复制
SELECT * FROM code_postals P INNER JOIN communes C ON P.code_commune=C.code_commune;

在我的TypeScript数据存储库类中,我有以下代码:

代码语言:javascript
运行
复制
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等方法之间的区别,也不知道如何提出这个关联请求。

我是普利兹

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-01 16:49:19

如果一个城市可以有多个邮政编码,同时一个特定的邮政编码对几个城市来说是相同的,那么城市和邮政编码之间就有M:N的关系,需要像CommunesPostalCodes这样的第三个连接表。

代码语言:javascript
运行
复制
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'});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69394717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档