Cascade delete not working
I have this schema:
When I try to delete all the musics from an album I get this error:
Here's my delete:
I don't understand what I'm doing wrong
export const albums = pgTable('albums', {
id: uuid('id').notNull().primaryKey().defaultRandom(),
name: text('name').notNull().unique(),
gameId: uuid('game_id').notNull(),
});
export const albumsRelations = relations(albums, ({ one, many }) => ({
music: many(musics),
}));
export const musics = pgTable('musics', {
id: uuid('id').notNull().primaryKey().defaultRandom(),
name: text('name').notNull(),
url: text('url').notNull().unique(),
albumId: uuid('album_id')
.notNull()
.references(() => albums.id, { onDelete: 'cascade' }),
});
export const musicsRelations = relations(musics, ({ one, many }) => ({
album: one(albums, { fields: [musics.albumId], references: [albums.id] }),
musicsToAuthors: many(musicsToAuthors),
}));
export const authors = pgTable('authors', {
id: uuid('id').notNull().primaryKey().defaultRandom(),
name: text('name').notNull().unique(),
});
export const authorsRelations = relations(authors, ({ many }) => ({
musicsToAuthors: many(musicsToAuthors),
}));
// more in first commentexport const albums = pgTable('albums', {
id: uuid('id').notNull().primaryKey().defaultRandom(),
name: text('name').notNull().unique(),
gameId: uuid('game_id').notNull(),
});
export const albumsRelations = relations(albums, ({ one, many }) => ({
music: many(musics),
}));
export const musics = pgTable('musics', {
id: uuid('id').notNull().primaryKey().defaultRandom(),
name: text('name').notNull(),
url: text('url').notNull().unique(),
albumId: uuid('album_id')
.notNull()
.references(() => albums.id, { onDelete: 'cascade' }),
});
export const musicsRelations = relations(musics, ({ one, many }) => ({
album: one(albums, { fields: [musics.albumId], references: [albums.id] }),
musicsToAuthors: many(musicsToAuthors),
}));
export const authors = pgTable('authors', {
id: uuid('id').notNull().primaryKey().defaultRandom(),
name: text('name').notNull().unique(),
});
export const authorsRelations = relations(authors, ({ many }) => ({
musicsToAuthors: many(musicsToAuthors),
}));
// more in first commentWhen I try to delete all the musics from an album I get this error:
update or delete on table "musics" violates foreign key constraint "musics_to_authors_music_id_musics_id_fk" on table "musics_to_authors"update or delete on table "musics" violates foreign key constraint "musics_to_authors_music_id_musics_id_fk" on table "musics_to_authors"Here's my delete:
await db.delete(musics).where(eq(musics.albumId, albumId))await db.delete(musics).where(eq(musics.albumId, albumId))I don't understand what I'm doing wrong