You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Eloquent无法更新updated_at字段问题求助

解决Laravel中无法更新updated_at字段的问题

问题根源

  1. 查询构造器的局限性:你使用的是DB门面的查询构造器,Laravel自动维护created_at/updated_at的机制仅对Eloquent模型生效,查询构造器不会自动处理时间戳字段。
  2. 重复查询的无效性:你连续两次调用$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模型可以自动维护时间戳,还能简化操作:

  1. 创建对应模型(注意表名匹配):
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class QueueTable extends Model
{
    protected $table = 'queueTable'; // 指定对应的数据表名
}
  1. 控制器中使用模型操作:
$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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:25:51