【问题标题】:Laravel Mass Updates without touching timestampsLaravel 大规模更新而不触及时间戳
【发布时间】:2018-12-27 18:38:57
【问题描述】:

如果是单次更新,我们可以使用

$variable->timestamps = false;

但是如果我想在不触及时间戳的情况下批量更新。

目前我的代码是

$allapps = App::select('id','name','parent_id','view')->where('published',true)->whereNotIn('id', $excludeappsid)->update(['timestamps' => false],['view' => 0]);

但我得到错误

SQLSTATE[42S22]:未找到列:1054 中的未知列“时间戳” '字段列表'

有什么办法吗?

谢谢。

【问题讨论】:

  • 如何在同一个查询中进行选择和更新?
  • 这样不是违背了 updated_at 字段的目的吗?
  • 通过这个查询我只想重置浏览量计数器,所以我不需要更新 updated_at 字段

标签: laravel timestamp


【解决方案1】:

据我所知,这是不可能的。我认为这甚至是不可能的。

但是,您可以在没有 Eloquent 的情况下直接使用查询构建器,这不会更新时间戳。

\DB::table(with(App::class)->getTable())
    ->where('published', true)
    ->whereNotIn('id', $excludeappsid)
    ->update(['view' => 0]);

【讨论】:

    【解决方案2】:

    由于您的模型,您可以将时间戳标记为 false

    public $timestamps = false;
    

    或者你什么也做不了。 :)

        $allapps = App::select('id','name','parent_id','view')
                       ->where('published',true)
                       ->whereNotIn('id', $excludeappsid)
                       ->update(['view' => 0])
    

    【讨论】:

    • 如果我用那个改变触摸模型,我必须触摸这么多控制器
    • 而当您只更新您想要的内容而不搜索更新created_atupdated_at 时会发生什么?
    • 通过这个查询我只想重置浏览量计数器,所以我不需要更新 updated_at 字段,
    【解决方案3】:

    试试这个:

    $model = new App();
    $model->timestamps = false;
    App::setModel($model)
        ->where('published',true)
        ->whereNotIn('id', $excludeappsid)
        ->update(['view' => 0]);
    

    【讨论】:

    • 请解释你的答案。
    • Laravel Eloquent Builder 在更新期间尝试“addUpdatedAtColumn”,如果模型有 updated_at 列,Eloquent Builder 会将此列添加到值数组中。对此进行处理时,该方法将检查类属性“$model”是否使用时间戳。如果您尝试暂时禁用时间戳,您可以在模型实例中将时间戳属性设置为 false 并在运行时传递该模型。
    【解决方案4】:

    您可以通过以下查询实现您的目标:

    App::select('id','name','parent_id','view')
        ->where('published',true)
        ->whereNotIn('id', $excludeappsid)
        ->update([
            'view' => 0,
    
            // Change updated_at column if its different from yours
            'updated_at' => \DB::raw('updated_at'),
        ]);
    

    实际上它会更新 updated_at 列,但 查询会用旧值更改它

    【讨论】:

      猜你喜欢
      • 2013-09-25
      • 2014-05-21
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 2014-09-30
      相关资源
      最近更新 更多