【问题标题】:Automatically use Timestamp in Laravel 5.4 Query builder在 Laravel 5.4 查询构建器中自动使用时间戳
【发布时间】:2025-12-18 09:20:03
【问题描述】:

有没有办法在使用查询生成器时自动使用时间戳,目前我正在使用 CARBON。 这是我的代码:

DB::table('product_in_out')->insert(
                ['product_id'                   => $product_id,
                 'warehouse_id'                 => $warehouse_id, 
                 'balance_before'               => Product::getProductBalanceOf($action_id, $product_id),
                 'in'                           => $product_qty,
                 'out'                          => '0',
                 'after_balance'                => Product::getProductBalanceOf($action_id, $product_id)+$product_qty,
                 'action'                       => 'ProcurementReceipt',
                 'action_id'                    => $action_id,
                 'created_by'                   => auth()->user()->id,
                 'updated_by'                   => auth()->user()->id,
                 'is_active'                    => '1',
                 'created_at'                   =>  \Carbon\Carbon::now(), # \Datetime()
                 'updated_at'                   => \Carbon\Carbon::now(),# \Datetime() ]

            );

【问题讨论】:

    标签: laravel timestamp laravel-5.4


    【解决方案1】:

    字段 created_atupdate_at 是 Eloquent 的一部分。

    您需要使用 Eloquent 而不是查询构建器来将记录插入和更新到数据库中以进行自动时间处理。 Eloquent 会为你自动更新 updated_at 列,

    这里是路,

    如果您有型号名称产品,

    $product = new Product();
    $product->column_name = $column_value;
    ....
    ...
    $product->save();
    

    以上代码会在created_atupdated_at列自动添加时间戳。

    现在使用 Eloquent 更新您的记录,例如,

    $product = Product::find($id);
    $product->update_column_name = $update_value;
    ...
    ...
    $product->update();
    

    这将相应地更新您的updated_at 列值。

    希望你能理解。

    【讨论】:

    • 我明白了你的意思,所以这意味着自动时间戳只有雄辩的?
    • @MartneyAcha 是的,使用查询生成器,您必须手动完成
    • @MartneyAcha 很高兴它对您有所帮助。即使使用模型批量插入或更新,我的时间戳也有问题
    【解决方案2】:

    使用 Laravel 宏:
    https://medium.com/fattihkoca/laravel-auto-save-timestamps-with-query-builder-without-using-eloquent-123f7ebfeb92

    明智的做法是创建一个宏以避免每次都输入相同的内容。

    1. insertTs 方法使用created_at 数据将记录插入数据库:

    DB::table('users')->insertTs([ 'email' => 'john@example.com' ]);

    $id = DB::table('users')->insertGetIdTs([ 'email' => 'john@example.com' ]);

    1. updateTs 方法使用updated_at 数据将记录更新到数据库中:

    DB::table('users') ->where('id', 1) ->updateTs(['email' => 'john@example.com']);

    1. deleteTs 方法使用deleted_at 数据将记录删除到数据库中(软删除):

    DB::table('users') ->where('id', 1) ->deleteTs();

    【讨论】: