Laravel按id更新记录时报Call to a member function latest() on int错误怎么办
错误原因
Laravel 查询构造器的 update() 方法返回值为受影响的记录行数(整数类型),而非查询构造器实例,因此无法在 update() 后继续链式调用 latest()、first() 这类构造器方法,这就是报错 Call to a member function latest() on int 的根因。
解决方案
根据你的需求场景选择对应实现:
场景1:仅更新task_id对应的最新一条记录
写法1(兼容所有Laravel版本)
先查询到最新记录再针对性更新:
// 先取符合条件的最新记录 $latestTask = DB::table('task_tracker') ->where('task_id', $task_id) ->latest() ->first(); if ($latestTask) { DB::table('task_tracker') ->where('id', $latestTask->id) ->update([ 'task_status' => 'Paused', 'task_finished_at' => $finished_at, 'action_comment' => 'Task Paused' ]); }
写法2(Laravel 8+ 支持)
直接单条匹配更新,无需二次查询:
DB::table('task_tracker') ->where('task_id', $task_id) ->orderByDesc('id') ->limit(1) ->update([ 'task_status' => 'Paused', 'task_finished_at' => $finished_at, 'action_comment' => 'Task Paused' ]);
场景2:更新所有task_id匹配的记录后,返回最新的更新后记录
将更新和查询拆分为两个独立操作:
// 执行更新,返回受影响行数 $affectedCount = DB::table('task_tracker') ->where('task_id', $task_id) ->update([ 'task_status' => 'Paused', 'task_finished_at' => $finished_at, 'action_comment' => 'Task Paused' ]); // 单独查询更新后的最新记录 $latestUpdatedTask = DB::table('task_tracker') ->where('task_id', $task_id) ->latest() ->first();
内容的提问来源于stack exchange,提问作者sneha bharathi
相关产品推荐
相关产品推荐

