I have a table with called “songs” which contains songs that have a “title”.
I also have a table called “artists” which contains artists that have a “spotify_id”.
A song can have many artist and an artist can blog to many songs so I have a pivot table “artist_song” which connects the “songs” and “artists” tables
In my models I have...
class Song extends Model
{
public function Artists() {
return $this->belongsToMany('App\Models\Artist');
}
}
class Artist extends Model
{
public function Songs() {
return $this->belongsToMany('App\Models\Song');
}
}
Via an API call this response comes in (extremely minified to only contain elements needed for this issue)
{
"artists" : [ {
"id" : “Artist1”
}, {
"id" : “Artist2”
} ],
"name" : “Cool Song“,
}
So far so good. Now I want to check if the song exists in the database by it’s title and all artists for this song.
The result can only be positive if the title and all artists are identical. Based on the example, should the song "Cool Song" exist in the database with “Artist1” and “Artist2” and the API call returns “Cool Song“ with only “Artist1”, the result of the query should be negative because not identical.
The amount of artists will be variable depending on the song. Most songs only have one artist but some songs can have a lot of artists.
What would the Eloquent query look like? A very helpful colleague quickly typed something like this on a notepad.
$artists = $track->artists;
$existingSong = Song::with('Artists', function($query) use ($artists) {
foreach($artists as $artist) {
$query .= $query->where('spotify_id', $artist->id);
}
return $query;
})->get()->where('title', $track->name);
return $existingSong;
But this results in this error:
ErrorException in Str.php line 72:
mb_strpos() expects parameter 1 to be string, object given
Thanks!