【问题标题】:How to update field when delete a row in laravel在laravel中删除一行时如何更新字段
【发布时间】:2014-10-19 14:42:08
【问题描述】:

让我有一个名为customer 的表,其中客户表有一个名为deleted_by 的字段。 我在customer 模型中实现softDelete。现在我想在删除行时更新deleted_by。这样我就可以追踪谁删除了这一行。

我确实在谷歌上搜索过,但我没有找到任何东西。

我使用 laravel 4.2.8 & Eloquent

【问题讨论】:

标签: laravel laravel-4 eloquent


【解决方案1】:

您可以使用以下方式更新该字段:

$customer = Customer::find(1); // Assume 1 is the customer id

if($customer->delete()) { // If softdeleted

    DB::table('customer')->where('id', $customer->id)
      ->update(array('deleted_by' => 'SomeNameOrUserID'));
}

另外,您可以在一个查询中完成:

// Assumed you have passed the id to the method in $id
$ts = Carbon\Carbon::now()->toDateTimeString();
$data = array('deleted_at' => $ts, 'deleted_by' => Auth::user()->id);
DB::table('customer')->where('id', $id)->update($data);

两者都在一个查询中完成,softDelete 并记录了deleted_by

【讨论】:

  • 它有效。我接受这个答案。但我不能投票,因为我的声誉不足以投票
【解决方案2】:

这样的事情是要走的路:

// override soft deleting trait method on the model, base model 
// or new trait - whatever suits you
protected function runSoftDelete()
{
    $query = $this->newQuery()->where($this->getKeyName(), $this->getKey());

    $this->{$this->getDeletedAtColumn()} = $time = $this->freshTimestamp();

    $deleted_by = (Auth::id()) ?: null;

    $query->update(array(
       $this->getDeletedAtColumn() => $this->fromDateTime($time), 
       'deleted_by' => $deleted_by
    ));
}

那么你只需要:

$someModel->delete();

它已经完成了。

【讨论】:

  • +1,我喜欢这个想法,但我也会传递一个参数来选择性地更新deleted_by 字段。 If($deleted_by) {...}.
  • @WereWolf-TheAlpha 是的,这也可以。这取决于所需的功能。提供的只是一个如何有效处理它的示例。
  • 注意,如果您使用原始特征并创建一个新特征来覆盖runSoftDelete() 方法,这将不起作用。它返回此致命错误:Trait method runSoftDelete has not been applied, because there are collisions with other trait methods on XXX 其中XXX 是您的型号名称。
  • @JeremyHarris Obvioulsy,这就是特征在 PHP 中的工作方式。但是.. 救援的别名 :) 如果你想覆盖新特征中的方法,那么只需使用 use SoftDeletes { runSoftDelete as unusedSoftDelete; } 就不会发生冲突。
  • 啊哈,非常好。我不知道特征别名。
【解决方案3】:

我知道这是一个老问题,但您可以做的(在客户模型中)如下......

public function delete() 
{
    $this->deleted_by = auth()->user()->getKey();
    $this->save();

    return parent::delete();
}

这仍然允许软删除,同时在删除之前设置另一个值。

【讨论】:

    【解决方案4】:

    我宁愿为此使用Model Event

    <?php
    class Customer extends \Eloquent {
        ...
        public static function boot() {
            parent::boot();
    
            // We set the deleted_by attribute before deleted event so we doesn't get an error if Customer was deleted by force (without soft delete).
            static::deleting(function($model){
                $model->deleted_by = Auth::user()->id;
                $model->save();
            });
        }
        ...
    }
    

    然后你就像往常一样删除它。

    Customer::find(1)->delete();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-01
      • 2021-03-05
      • 2018-08-09
      • 2016-03-31
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 2015-07-30
      相关资源
      最近更新 更多