D_J
D_J

Reputation: 55

How to add Sequelize Association into Model

I am new to Typescript and trying to connect with the Mysql database I have created the following files

User.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
}
});

Address.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
}});

here I want to add hasMany association on User model user hasMany => address[] How can I achieve that? what I am looking here how to use sequelize in typescript how to create setup and save data into tables ? Thank you in advance

Upvotes: 0

Views: 743

Answers (1)

Dhaval Darji
Dhaval Darji

Reputation: 513

users.hasMany(city_data, {
  foreignKey: "address",
});

Or

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

how to add :

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;

Upvotes: 1

Related Questions