Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strongloop loopback: how to save many-to-many relationship

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?

like image 870
transient_loop Avatar asked Oct 13 '25 10:10

transient_loop


1 Answers

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:

  • Add a song to a playlist: PUT /api/playlist/:id/song/rel/:fk
  • Remove a song from a playlist: DELETE /api/playlist/:id/song/rel/:fk

Note 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.

like image 86
conradj Avatar answered Oct 15 '25 11:10

conradj