Typescript Sequelize Add Relantionship crashing the app

Viewed 16

Hello I started learning typescript, made one admin model, and role model, when I try to add belongs to to roleId I am getting error. Can someone pls check what can be the issue , I am not able to resolve it.

import { Admin } from '@interfaces/admin.interface';
import RoleModel from './role.model';

export type AdminCreationAttributes = Optional<Admin, 'id' | 'email'>;

export class AdminModel extends Model<Admin, AdminCreationAttributes> implements Admin {
  public id: number;
  public email: string;
  public role_id: number;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

export default function (sequelize: Sequelize): typeof AdminModel {
  AdminModel.init(
    {
      id: {
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER,
      },
      email: {
        allowNull: false,
        type: DataTypes.STRING(45),
      },
      role_id: {
        allowNull: false,
        type: DataTypes.INTEGER,
      },
    },
    {
      tableName: 'Admins',
      sequelize,
    },
  );

  AdminModel.hasMany(RoleModel, {foreignKey: 'role_id', as: 'roles', targetKey: 'id'});
  return AdminModel;
}
1 Answers

First, you didn't import DataTypes from sequelize package.
Second, you need to register all models and only after that register all associations. To get the idea how to do it see my other answer to the similar problem

Related