mysql - 如何在 Destroy 函数中删除具有多个参数的数据 - Laravel

标签 mysql laravel orm eloquent laravel-5.8

我正在做简单的增删改查,如果 user_idhymn_idfavourite_list 表中的匹配,我想删除收藏列表表的列

这是我的删除路线:

Route::resource('fav_hymns', 'Api\favouriteController');
Route::delete('fav_hymns/{user_id}/{hymn_id}/', 'Api\favouriteController@destroy');

以及我在资源favouriteController中的“销毁”功能

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 (在路由中)甚至不存在并且甚至不匹配,它会删除所有列,它正在删除所有列。

帮助将不胜感激,谢谢

最佳答案

您的删除 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()

关于mysql - 如何在 Destroy 函数中删除具有多个参数的数据 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56522511/

相关文章:

mysql - 从数据库中获取数据并设置到jsp文件中

php - 拉维尔 4 : can one model serve several DB tables?

php - 拉维尔 5.3 : Best way to retrieve data between dates and group them in weeks?

laravel - 何时在 Laravel 5 中使用 belongsToMany 与 hasMany

node.js - 为什么在 Node 中插入数据后没有正确响应?

sql - 如何在sequelize中将外键引用到另一个外键?

mysql - SQL : count records per 5 minute intervals (including zeros)

php - 实现关键字比较方案(反向搜索)

php - 获取符合条件的列的总和

php - 如何从中间件向 Laravel 的 IOC 容器添加对象