#Many to many relations with join table using Sequelize

1 messages · Page 1 of 1 (latest)

wise prism
#

Hi everyone,

I have the 3 following models:

import {
  Column,
  Model,
  Table,
  DataType,
  BelongsToMany,
  ForeignKey,
  BelongsTo,
} from 'sequelize-typescript';
import { User } from '../user/user.entity';
import { UserProject } from './user-project.entity';
import { Category } from './category.entity';

@Table
export class Project extends Model<Project> {
  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  name: string;

  @BelongsToMany(() => User, () => UserProject)
  Users: Array<User & { UserProject: UserProject }>;

  @ForeignKey(() => Category)
  @Column
  categoryId: number;

  @BelongsTo(() => Category)
  category: Category;
}
import {
  Column,
  Model,
  Table,
  DataType,
  BelongsToMany,
} from 'sequelize-typescript';
import { Project } from 'src/project/project.entity';
import { UserProject } from 'src/project/user-project.entity';

@Table
export class User extends Model<User> {
  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  username: string;

  @Column({
    type: DataType.STRING,
    allowNull: false,
    unique: true,
  })
  email: string;

  @BelongsToMany(() => Project, () => UserProject)
  projects: Array<Project & { UserProject: UserProject }>;
}
import {
  Column,
  Model,
  Table,
  DataType,
  ForeignKey,
} from 'sequelize-typescript';
import { User } from '../user/user.entity';
import { Project } from './project.entity';

@Table
export class UserProject extends Model<UserProject> {
  @ForeignKey(() => User)
  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  userId: number;

  @ForeignKey(() => Project)
  @Column({
    type: DataType.INTEGER,
    allowNull: false,
  })
  projectId: number;

  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  role: string;
}

Everything is correctly created in database.
When I tried to fetch project from the database, including the join table, I can't retrieve it, although the SQL is correct.

#

and here is how I fetch data from my service:

  findAllProjects() {
    return this.projectModel.findAll({
      include: [
        {
          model: User,
          through: { attributes: ['role'] },
        },
      ],
    });
  }