I have the following relationship defined:
{
"name": "playlist",
"base": "PersistedModel",
"relations": {
"songs": {
"type": "hasAndBelongsToMany",
"model": "song",
"foreignKey": ""
}
}
}
So a Song hasAndBelongsToMany Playlist. So far so good.
But when it comes to adding songs to a playlist, I am confused.
Ideally I'd like, for example, to be able to add the new songs in the same call of the playlist create endpoint. I have no idea how to do that, and the docs are quite poor imho.
It seems I have to do a POST on /playlists/:id/songs in order to associate songs to playlists? But then, I don't want to create new songs, just add existing songs to a playlist. Would that work this way? Wouldn't a POST at the mentioned URL add (and wanting to create) new songs?
BTW, using postgresql as backend.
What's the correct way to do that?
When you create a hasAndBelongsToMany relationship Loopback exposes add and remove JS methods as documented. However I can't find any documentation on how it is exposed in the API, but this pull request explains how to do it as follows:
PUT /api/playlist/:id/song/rel/:fkDELETE /api/playlist/:id/song/rel/:fkNote that this assumes that you have a PlaylistSong link table and Loopback Model, with PlaylistId and SongId fields and all of the correct relationships set up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With