Laravel Eloquent无法更新updated_at字段问题求助
解决Laravel中无法更新updated_at字段的问题
问题根源
- 查询构造器的局限性:你使用的是
DB门面的查询构造器,Laravel自动维护created_at/updated_at的机制仅对Eloquent模型生效,查询构造器不会自动处理时间戳字段。 - 重复查询的无效性:你连续两次调用
$check->update(),第一次执行后目标记录的status已改为Inactive,第二次执行原查询时,where('status','Active')的条件不再匹配,导致没有记录被更新,updated_at字段自然无变化。
修正方案(基于查询构造器)
将两次更新操作合并为一次,确保仅执行一次有效查询,同时修改status和updated_at:
$check = \DB::table('queueTable') ->where('category', $catName2) ->where('status', 'Active') ->where('skipped', '0') ->whereDate('created_at', '=', now()) ->orderBy('queue', 'ASC') ->limit(1); $counter = \DB::table('queueTable') ->where('category', $catName2) ->where('status', 'Inactive') ->whereDate('created_at', '=', now()) ->count(); \DB::table('CurrentQueue')->where('id', 2)->update(['DoneQueue' => $counter + 1]); // 合并更新,一次完成字段修改 $check->update([ 'status' => 'Inactive', 'updated_at' => now() // Laravel会自动处理日期格式,无需手动format ]);
更优方案:使用Eloquent模型(Laravel最佳实践)
使用Eloquent模型可以自动维护时间戳,还能简化操作:
- 创建对应模型(注意表名匹配):
namespace App\Models; use Illuminate\Database\Eloquent\Model; class QueueTable extends Model { protected $table = 'queueTable'; // 指定对应的数据表名 }
- 控制器中使用模型操作:
$check = \App\Models\QueueTable::where('category', $catName2) ->where('status', 'Active') ->where('skipped', '0') ->whereDate('created_at', '=', now()) ->orderBy('queue', 'ASC') ->first(); $counter = \App\Models\QueueTable::where('category', $catName2) ->where('status', 'Inactive') ->whereDate('created_at', '=', now()) ->count(); \DB::table('CurrentQueue')->where('id', 2)->update(['DoneQueue' => $counter + 1]); if ($check) { $check->status = 'Inactive'; $check->save(); // Eloquent会自动更新updated_at字段 // 若仅需更新时间戳,可直接调用:$check->touch(); }
内容的提问来源于stack exchange,提问作者Wedman Hutahaean
相关产品推荐
相关产品推荐

