Trying to join parent / primary table to child / foreign table in sequelize

Viewed 30

I'm trying to get all my articles data from articles table but also user data from users table i've made. I using sequelize to build database to MySQL database and also as a ORM, here's the snippet code

USER TABLE

    const User = sequelize.define('users', ({
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  nama: {
    type: DataTypes.STRING(50),
    allowNull: false,
  },
  email: {
    type: DataTypes.STRING(50),
    allowNull: false,  
  },
  password: {
    type: DataTypes.STRING(50),
    allowNull: false,
  }
}))

ARTICLES CODE

    const Articles = sequelize.define('articles', ({
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  gambar: {
    type: DataTypes.STRING,
    allowNull: false
  },
  userId: {
    type: DataTypes.BIGINT,
    allowNull: false,
  }
}))

the relation

    User.hasMany(Articles, {
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE',
})
Articles.belongsTo(User, {
  foreignKey: 'userId'
})

the ORM i've try

Articles.findAll({
    include: [User]
  })

it is always return that users table is not associated to artiles

1 Answers

You have to use as key word during creating relation ship.

Articles.belongsTo(User, {
 as: 'user',
 foreignKey: 'userId'
})

and then update form

Articles.findAll({include: [{
 model: model.User,
 as: 'user'
}]})
Related