Home > database >  How to properly make a table association using hasOne, belongsTo using Sequelize and express js
How to properly make a table association using hasOne, belongsTo using Sequelize and express js

Time:08-30

I am working on expre6ssjs with sequelize version 6. I have User and Message and I need to make one to many relationship between them.

here is what I have so far

import { Sequelize, DataTypes } from "sequelize";

const sequelize = new Sequelize(
  'messagenger',
  'mysql',
  'password',
  {
    host: 'localhost',
    dialect: 'mysql'
  }
);

sequelize.authenticate().then(() => {
  console.log('Connection has been established successfully.');
}).catch((error) => {
  console.error('Unable to connect to the database: ', error);
});

const User = sequelize.define("users", {
  name: {
    type: DataTypes.STRING,
    allowNull: false
  }
});

const Message = sequelize.define("messages", {
  text: {
    type: DataTypes.STRING,
    allowNull: false
  },
});

sequelize.sync({ force: true }).then(() => {

  // User.hasMany(Message, {
  //   foreignKey: "user_id",
  //   as: "messages"
  // });
  // Message.belongsTo(User, {
  //   foreignKey: "user_id",
  //   as: "users"
  // });

  // Message.belongsTo(User, {
  //   foreignKey: "userId",
  //   as: "user"
  // })

  Message.belongsTo(User);
  User.hasMany(Message);

}).catch((error) => {
  console.error('Unable to create table : ', error);
});

this is my messages table.

mysql> describe messages;
 ----------- -------------- ------ ----- --------- ---------------- 
| Field     | Type         | Null | Key | Default | Extra          |
 ----------- -------------- ------ ----- --------- ---------------- 
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| text      | varchar(255) | NO   |     | NULL    |                |
| createdAt | datetime     | NO   |     | NULL    |                |
| updatedAt | datetime     | NO   |     | NULL    |                |
 ----------- -------------- ------ ----- --------- ---------------- 
4 rows in set (0.00 sec) 

I have tried a couple of versions as you can see in the comments. but nothing worked. https://sebhastian.com/sequelize-hasone/ I was following this tutorial and this does not look complicated at all.

By the way, I have been searching for the answer for a while now. And I know people also use a different approach such as referenced in the table definition. But my goal is to use hasMany, belongsTo, these methods as they are very explicit.

Any advice will help me a lot.

Thank you in advance.

CodePudding user response:

You need to define all models and associations BEFORE calling sync in order to Sequelize to know all about what tables and foreign key fields and foreign key constraints it needs to create.

const User = sequelize.define("users", {
  name: {
    type: DataTypes.STRING,
    allowNull: false
  }
});

const Message = sequelize.define("messages", {
  text: {
    type: DataTypes.STRING,
    allowNull: false
  },
});

Message.belongsTo(User);
User.hasMany(Message);

sequelize.sync({ force: true }).then(() => {
  console.info('Model synchronization completed');
}).catch((error) => {
  console.error('Unable to create table : ', error);
});
  • Related