【问题标题】:How to add Sequelize Association into Model如何将 Sequelize 关联添加到模型中
【发布时间】:2021-08-02 20:15:33
【问题描述】:

我是 Typescript 的新手并尝试连接 Mysql 数据库,我创建了以下文件

用户.ts

export const UserData = sequelize.define('users', {
id: {
    type:Sequelize.INTEGER,
    autoIncrement:true,
    allowNull:false,
    primaryKey:true
},
 name: {
    type:Sequelize.STRING,
    allowNull:false
},
address: {
    type:Sequelize.INTEGER,
    allowNull:false
}
});

地址.ts

export const CityData = sequelize.define('city_data', {
id: {
    type:Sequelize.INTEGER,
    autoIncrement:true,
    allowNull:false,
    primaryKey:true
},
city: {
    type:Sequelize.STRING,
    allowNull:false
},
house_no: {
    type:Sequelize.INTEGER,
    allowNull:false
}});

这里我想在用户模型 user hasMany => address[] 上添加 hasMany 关联,我该如何实现? 我在这里看什么 如何在打字稿中使用 sequelize 如何创建设置并将数据保存到表中? 提前谢谢你

【问题讨论】:

    标签: mysql node.js typescript sequelize.js sequelize-typescript


    【解决方案1】:
    users.hasMany(city_data, {
      foreignKey: "address",
    });
    

    或者

    UserData.hasMany(CityData, {
      foreignKey: "address",
    });
    

    如何添加:

    const UserData = sequelize.define('users', {
    id: {
        type:Sequelize.INTEGER,
        autoIncrement:true,
        allowNull:false,
        primaryKey:true
    },
     name: {
        type:Sequelize.STRING,
        allowNull:false
    },
    address: {
        type:Sequelize.INTEGER,
        allowNull:false
    }
    });
    
    UserData.hasMany(city_data, {
      foreignKey: "address",
    });
    
    export UserData;
    

    【讨论】:

    • 我需要在导出前添加这个吗?还是像其他属性一样添加到 city_data 对象中?
    猜你喜欢
    • 2021-03-20
    • 2019-08-18
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2013-03-01
    • 2017-07-01
    相关资源
    最近更新 更多