laravel 5.4 如何使用自定义异常处理查询异常

laravel 5.4 how to handle query exception with custom exception

每当我尝试删除子项中具有相关歌曲的艺术家时 table。 它 returns 这个错误。

QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`laravel`.`artist_song`, CONSTRAINT `artist_song_artist_id_foreign` FOREIGN KEY (`artist_id`) REFERENCES `artists` (`id`)) (SQL: delete from `artists` where `id` = 1)

这就是我想要的。保护父级 table,但我想要的是让最终用户看到这样的消息“您不能删除具有相关歌曲的艺术家,请先删除该艺术家的所有歌曲”。那么如何才能我用自定义异常捕捉到了这个?

我认为您不需要在这里依赖数据库异常。当有人选择删除艺术家时,您应该验证艺术家是否有任何歌曲,如果有,您应该重定向消息。

假设您在 Artist 模型关系中定义如下:

public function songs()
{
   return $this->hasMany(Song::class);
}

在控制器中你可以使用这样的代码:

public function destroy($artistId)
{
    $artist = Artist::findOrFail($artistId);
    if ($artist->songs()->count()) {
       return redirect()->back()->with('message','You cannot delete ...');  
    }
    $artist->delete();
    return redirect()->route('artists.index'); 
}