Why sequelize ignore the references property?

Tags: , ,



I using sequelize:

 "dependencies": {
    "@types/node": "^14.14.6",
    "sequelize": "^6.3.5",
    "tedious": "^9.2.1",
    "typescript": "^4.0.5"
  }

I have two tables in my sql database: user and task.

task_user_id in task table has references to user table:

taskUserId: {
    type: DataTypes.UUID,
    allowNull: true,
    references: {
     model: "user",
     key: "id",
    },
    field: "task_user_id",
},

So why when I run findAll function I don’t get the user details inside the object I’m getting?

const u = await Task.findAll({ raw: true });

Maybe something missing in my code?

task.ts:

/* jshint indent: 2 */

import { DataTypes, Model, Sequelize } from "sequelize";

export interface TaskAttributes {
  id?: number;
  taskUserId?: string;
  name?: string;
}

export class Task
  extends Model<TaskAttributes, TaskAttributes>
  implements TaskAttributes {
  id?: number;
  taskUserId?: string;
  name?: string;

  static initModel(sequelize: Sequelize) {
    Task.init(
      {
        id: {
          autoIncrement: true,
          type: DataTypes.INTEGER,
          allowNull: false,
          primaryKey: true,
        },
        taskUserId: {
          type: DataTypes.UUID,
          allowNull: true,
          references: {
            model: "user",
            key: "id",
          },
          field: "task_user_id",
        },
        name: {
          type: DataTypes.STRING(600),
          allowNull: true,
          field: "task_name",
        },
      },
      {
        sequelize,
        tableName: "task",
        schema: "dbo",
        timestamps: false,
      }
    );
    return Task;
  }
}

user.ts:

/* jshint indent: 2 */

import { DataTypes, Model, Sequelize } from 'sequelize';

export interface UserAttributes {
  id?: string;
  name?: string;
  email?: string;
  password?: string;
}

export class User extends Model<UserAttributes, UserAttributes> implements UserAttributes {
  id?: string;
  name?: string;
  email?: string;
  password?: string;

  static initModel(sequelize: Sequelize) {
    User.init(
      {
        id: {
          type: DataTypes.UUID,
          allowNull: false,
          primaryKey: true,
        },
        name: {
          type: DataTypes.STRING(80),
          allowNull: false,
        },
        email: {
          type: DataTypes.STRING(255),
          allowNull: false,
        },
        password: {
          type: DataTypes.STRING,
          allowNull: false,
        },
      },
      {
        sequelize,
        tableName: 'user',
        schema: 'dbo',
        timestamps: false,
      }
    );
    return User;
  }
}

Answer

In order to request a model with linked models you should add explicit associations between models like this:

Task.belongTo(User, { foreignKey: 'task_user_id' })

And after that you can query tasks along with a linked user like this:

const u = await Task.findAll({ raw: true, include: [User] });


Source: stackoverflow