sequelize-typescript: Unable to create relationship between more than 2 tables

I am trying to create a relationship between 3 tables but I am having difficulty doing so because of unique constraints set on the foreign key on the joining table.

What I am trying to achieve is a user, who is assigned to a group and within that group has certain permissions to do things (i.e. a CRUD matrix) with the end result being something along the lines of this

{
  "emailAddress": "test@example.com",
  "id": "UUID string goes here",
  "username": "Test user",
  "tasks": {
    "exampleTask": [
      "create",
      "update"
    ],
    "otherTask": [
      "create",
      "read",
      "update",
      "delete"
    ]
  }
}

This is what I have

// user.model.ts

@Table
export class User extends Model<User> {
  @Column({
    allowNull: false,
    type: DataType.STRING,
    unique: true,
    validate: {
      notEmpty: true,
      isEmail: true
    }
  }) public emailAddress: string;

  @Column({
    defaultValue: DataType.UUIDV4,
    primaryKey: true,
    type: DataType.UUID
  }) public id: string;

  @Column({
    type: DataType.STRING,
    allowNull: false,
    validate: {
      notEmpty: true
    }
  }) public password: string;

  @BelongsToMany(
    () => Permission,
    () => TaskPermission
  ) public permissions: Permission[];

  @BelongsToMany(
    () => Task,
    () => UserTask
  ) public tasks: Task[];

  @Column({
    allowNull: false,
    type: DataType.STRING,
    unique: true,
    validate: {
      notEmpty: true
    }
  }) public username: string;
}

// task.model.ts

@Table
export class Task extends Model<Task> {
  @Column({
    defaultValue: DataType.UUIDV4,
    primaryKey: true,
    type: DataType.UUID
  }) public id: string;

  @Column({
    allowNull: false,
    type: DataType.STRING,
    validate: {
      notEmpty: true
    }
  }) public name: string;

  @BelongsToMany(
    () => Permission,
    () => TaskPermission
  ) public permissions: Permission[];
}

// permission.model.ts

@Table
export class Permission extends Model<Permission> {
  @Column({
    defaultValue: DataType.UUIDV4,
    primaryKey: true,
    type: DataType.UUID
  }) public id: string;

  @Column({
    allowNull: false,
    type: DataType.STRING,
    validate: {
      notEmpty: true
    }
  }) public name: string;
}

// task-permission.model.ts

@Table
export class TaskPermission extends Model<TaskPermission> {
  @Column({
    defaultValue: DataType.UUIDV4,
    primaryKey: true,
    type: DataType.UUID
  }) public id: string;

  @ForeignKey(
    () => Permission
  )
  @Column
  public permissionId: string;

  @ForeignKey(
    () => Task
  )
  @Column
  public taskId: string;

  @ForeignKey(
    () => User
  )
  @Column
  public userId: string;
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 16 (8 by maintainers)

Most upvoted comments

Yes, it should 😃