Check if genre exists before creating a new one

This commit is contained in:
Josef Citrine 2016-09-25 15:07:20 +01:00
parent 66ffd7714d
commit 9b31b48f37

View file

@ -126,10 +126,33 @@ class ParseTrackTagsCommand extends CommandBase
* @return int * @return int
*/ */
protected function getGenreId(string $genreName) { protected function getGenreId(string $genreName) {
return Genre::firstOrCreate([ $existingGenre = Genre::withTrashed()
'name' => $genreName, ->where('name', $genreName)->first();
'slug' => Str::slug($genreName)
])->id; if ($existingGenre == null) {
// Has never existed, create new genre
return Genre::create([
'name' => $genreName,
'slug' => Str::slug($genreName)
])->id;
} else {
// Exists in db, has it been deleted?
$visibleGenre = Genre::where('name', $genreName)->first();
if ($visibleGenre == null) {
// This genre was deleted. Let's bring it back
// instead of creating a new one
$existingGenre->restore();
return $existingGenre->id;
} else {
// It's fine, just return the ID
return $visibleGenre->id;
}
}
} }
/** /**