Skip to content

Deleting in a many-to-many relationship #1609

Answered by groue
phi161 asked this question in Q&A
Discussion options

You must be logged in to vote

Hello @phi161,

I was wondering if it's possible to have an album automatically removed after I delete its last song.

When I delete a song I can see the entry from albumSong removed, but the referenced album row is still there.

Indeed, deleting albums that have no song has to be done by the application.

Assuming you have defined an Album.albumSongs hasMany association, you can run the following line:

// Delete empty albums that do not contain any song.
try Album.having(Album.albumSongs.isEmpty).deleteAll(db)

See Association Aggregates for more information about isEmpty.

I also tried to delete rows from albumSong directly, but cascade didn't work for song/album.

When rows are deleted from

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@phi161
Comment options

Answer selected by phi161
Comment options

You must be logged in to vote
1 reply
@groue
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants