使用 Eloquent 模型调用 destroy 方法进行删除的时候,莫名其妙的发现多了一次查询

当想要调用Eloquent模型 删除数据的时候,通过debug查看发现多了一条查询语句:

代码如下:

public function destroy(GroupModel $model, $id)
{
    $model->destroy($id);
    return back()->with('success', '删除成功');
}

路由在注册的时候,用的是资源路由

Route::prefix('groups')->resource('groups', 'GroupsController', ['name'=>[
            'index' =>  'index',
            'create'    =>  'create',
            'store' =>  'store',
            'show'  =>  'show',
            'edit'  =>  'edit',
            'update'    =>  'update',
            'destroy'   =>  'destroy'
        ]])->parameters(['groups'=>'gid']);

没有在模型中定义任何方法,只定义了主键属性
看到这么多兄弟帮忙,非常感谢大家帮我解答疑惑。
我按照一些做法试了试,如果说在删除的时候指定一个where条件,然后调用delete方法,就不会多出那一条查询sql。
如果用destroy方法删除,就会多出一条查询sql.

非常感谢大家!!!!我看了一下destroy的源码

public static function destroy($ids)
    {
        // We'll initialize a count here so we will return the total number of deletes
        // for the operation. The developers can then check this number as a boolean
        // type value or get this total count of records deleted for logging, etc.
        $count = 0;

        if ($ids instanceof BaseCollection) {
            $ids = $ids->all();
        }

        $ids = is_array($ids) ? $ids : func_get_args();

        // We will actually pull the models from the database table and call delete on
        // each of them individually so that their events get fired properly with a
        // correct set of attributes in case the developers wants to check these.
        $key = ($instance = new static)->getKeyName();
         // 在删除之前先进行了一次查询
        foreach ($instance->whereIn($key, $ids)->get() as $model) {
            if ($model->delete()) {
                $count++;
            }
        }

        return $count;
    }

使用destroy方法在删除之前先进行了一次查询,所以才多出了那一条sql

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

感谢大家,根据大家的回答,我看了一下源码,发现destroy这个方法在删除之前先进行了一次查询,所以才会出现两条sql.
但是我不明白的是,为什么要多查询一次呢?
这样不是更浪费资源吗?

3年前 评论
自由与温暖是遥不可及的梦想 3年前
Seanhepps (作者) (楼主) 3年前
自由与温暖是遥不可及的梦想 3年前
L学习不停 3年前
dxxwj 3年前
讨论数量: 6
Summer

第一个 SQL 是路由模型绑定自动查询的,第二个 SQL 是你的删除调用。

查阅:路由《Laravel 7 中文文档》

3年前 评论

改成这样试试:

public function delete(GroupModel $model)
{
    return $model->destroy();
}

原因参考:路由《Laravel 7 中文文档》

3年前 评论
GeorgeKing 3年前
Seanhepps (楼主) 3年前
Summer

第一个 SQL 是路由模型绑定自动查询的,第二个 SQL 是你的删除调用。

查阅:路由《Laravel 7 中文文档》

3年前 评论

如果不需要对模型的属性做一些验证啥的,没必要绑定,直接根据ID删掉即可。

public function delete($id)
{
    return GroupModel::where('id', $id)->delete();
}
3年前 评论
自由与温暖是遥不可及的梦想

没有多查询。是执行了两次sql 第一次是拿到数据。第二次是执行删除

3年前 评论

感谢大家,根据大家的回答,我看了一下源码,发现destroy这个方法在删除之前先进行了一次查询,所以才会出现两条sql.
但是我不明白的是,为什么要多查询一次呢?
这样不是更浪费资源吗?

3年前 评论
自由与温暖是遥不可及的梦想 3年前
Seanhepps (作者) (楼主) 3年前
自由与温暖是遥不可及的梦想 3年前
L学习不停 3年前
dxxwj 3年前
nfangxu

应该是为了触发事件吧, 批量操作的时候, 是没办法触发删除事件的, 只有单个delete 的时候才能触发

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!