這是需要應用的規則。使用樣本數據進行測試,並按需要運行。
use Illuminate\Validation\Rule;
$playlist_id = request('playlist_id');
$rules = [
'song_id' => Rule::unique('tableA')->where(function ($query) use ($playlist_id) {
$query->where('playlist_id', $playlist_id);
})
];
樣品條件
DB data
song_id playlist_id
2 34
3 34
Request data
song_id playlist_id validation
2 34 fail
3 34 fail
4 34 success
2 35 success
3 35 success
樣品測試代碼
$data = [
'song_id' => 2,
'playlist_id' => 34,
];
$playlist_id = $data['playlist_id'];
$validator = \Validator::make($data, [
'song_id' => Rule::unique('tableA')->where(function ($query) use ($playlist_id) {
$query->where('playlist_id', $playlist_id);
})
]);
if ($validator->fails()) {
// handle failed validation
}
聽起來像是你需要song_id'的'聯合鍵和'playlist_id',以防止在該表副本(我假設是'歌曲'和'播放列表'之間多對多的關鍵) –