我正在做简单的事情,如果user_id
表中有hymn_id
和favourite_list
匹配,我想删除收藏列表列表中的列
这是我的删除路线:
Route::resource('fav_hymns', 'Api\favouriteController');
Route::delete('fav_hymns/{user_id}/{hymn_id}/', 'Api\favouriteController@destroy');
和我在资源收藏夹控制器中的“销毁”功能
public function destroy($user_id,$hymn_id)
{
$favourite_list = favourite_list::where('user_id','=',$user_id, 'AND', 'hymn_id', '=', $hymn_id)->delete();
if (!$favourite_list) {
return response()->json([
'success' => false,
'message' => 'Error: List not found'
], 400);
}
if ($favourite_list) {
return response()->json([
'success' => true
]);
} else {
return response()->json([
'success' => false,
'message' => 'List could not be deleted'
], 500);
}
}
但是问题是,如果$user_id
匹配并且$hymn_id
(在路由中)甚至不存在并且甚至不匹配,它将删除所有列。 / p>
将不胜感激,谢谢
答案 0 :(得分:1)
您的删除where()
条件在这里不正确。你应该尝试。
try{
favourite_list::where('user_id', $user_id)
->where('hymn_id', $hymn_id)
->delete();
} catch(\Exception $e){
return response()->json([
'success' => false,
'message' => 'List could not be deleted'
], 500);
}
return response()->json([
'success' => true
]);
每个条件都应使用不同的where()
包装。如果您希望使用SQL格式,请尝试使用whereRaw()
。
答案 1 :(得分:0)
像这样
public function destroy($user_id,$hymn_id)
{
$favourite_lists =favourite_list::where('user_id', $user_id)
->where('hymn_id', $hymn_id)->get();
foreach($favourite_lists as $favourite_list)
{
$favourite_list->delete();
}
return response()->json("records deleted",200);
}