Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Typescript on delete cascade throwing errors

I've got a very straightforward FK relationship between Group and GroupAttendee. Whenever I call Group.destroy() I'm greeted with a foreign key constraint failure exception on the GroupAttendee entries. I understand how those constraints are supposed to work at the database level but I can't seem to get sequelize-typescript to create?/enforce? them.

I'm including a simplified version of my models to demonstrate my setup:

import { Model, Column, AllowNull, HasMany, ForeignKey, DataType, BelongsTo } from "sequelize-typescript";
import { User } from "./User";

class Group extends Model<Group> {

  @AllowNull(false)
  @Column
  title: string;

  @AllowNull(false)
  @Column
  startDate: Date;

  @AllowNull(false)
  @Column
  endDate: Date;

  @HasMany(() => GroupAttendee)
  attendees: GroupAttendee[];
}

class GroupAttendee extends Model<GroupAttendee> {

  @ForeignKey(() => User)
  @Column(DataType.INTEGER)
  userId: number;

  @ForeignKey(() => Group)
  @Column(DataType.INTEGER)
  groupId: number;

  @BelongsTo(() => Group, {
    onUpdate: "CASCADE",
    onDelete: "CASCADE",
    hooks: true
  })
  group: Group;
}

Has anyone gotten this to work?

like image 440
circuitBurn Avatar asked Sep 08 '26 05:09

circuitBurn


1 Answers

I think you should put cascade on Group Model , instead of GroupAttendee , like this :

@HasMany(() => GroupAttendee , {
    onUpdate: "CASCADE",
    onDelete: "CASCADE",
    hooks: true
})
attendees: GroupAttendee[];
like image 124
Vivek Doshi Avatar answered Sep 11 '26 04:09

Vivek Doshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!