使用 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
推荐文章: