This is rather complicated. I’ll try a explain as clearly as possible.
Models:
I have 3 models Track, Song and Artist. A track has one song, a song can belong to many tracks, a song can have many artists and an artist can belong to many songs. (see relationships below at "Models relationships")
Database tables:
The Database tables are tracks, songs, artists and artist_song (pivot). (see the fields below at "Database tables and fields")
Scenario:
Via an API call to the Spotify API data is returned. The returned JSON contains data from songs which have one or more artists. (see JSON return below at "Returned API data")
What I want to do:
For every song in the JSON…
- create a record in the songs table with the song info (“name” to “title” field)
- create a record in the tracks table with the ID of the song
- create a record for every artist in the artists table
- attache the artists to the correct songs via the pivot table.
With as few queries as possible
What I can do:
I am able create all records but with queries in loops which could result in too many DB queries.
I can write the 3 songs in one query (see last code block) but I don’t know how to proceed with writing the tracks and artist for these songs.
So...
Anyone willing to nudge me in the right direction?
Thanks!
Models relationships
// Track
public function song() {
return $this->belongsTo('App\Models\Song');
}
// Song
public function tracks() {
return $this->hasMany('App\Models\Track');
}
public function Artists() {
return $this->belongsToMany('App\Models\Artist');
}
// Artist
public function Songs() {
return $this->belongsToMany('App\Models\Song');
}
Database tables and fields (minimised to only the fields needed for this question)
tracks
- id
- song_id
songs
- id
- title
artists
- id
- name
artist_song
- song_id
- artist_id
Returned API data (example, minified to only the data needed for this question)
{
“songs”: [
{
"artists": [
{
"name": "Dreadzone"
}
],
"name": "Digital Mastermind",
},
{
"artists": [
{
"name": "Damian Marley"
},
{
"name": "Stephen Marley"
},
{
"name": "Rovleta Fraser",
}
],
"name": "Hey Girl",
},
{
"artists": [
{
"name": "The Wailers"
},
{
"name": "Alpha Blondy"
}
],
"name": "Jerusalem",
}
]
}
Inserting the 3 songs in one query
$songs = collect();
foreach ($spotifyTracksData->songs as $song) {
$songs->push(['title' => $song->name]);
}
$return = Song::insert($songs->toArray());