如何在laravel中删除行时更新字段

5 laravel eloquent laravel-4

让我有一个名为customercustomer表有一个名为的字段的表deleted_by.我softDeletecustomer模型中实现.现在我想deleted_by在行删除时更新.这样我就可以追踪删除这一行的人.

我在google上搜索它但我没有找到任何东西.

我使用laravel 4.2.8和Eloquent

The*_*pha 6

您可以使用以下内容更新字段:

$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'));
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以在一个查询中执行此操作:

// 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);
Run Code Online (Sandbox Code Playgroud)

两者都在一个查询中完成,softDelete并且也被记录deleted_by.


Jar*_*zyk 5

这样的事情是要走的路:

// 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
    ));
}
Run Code Online (Sandbox Code Playgroud)

那么你只需要:

$someModel->delete();
Run Code Online (Sandbox Code Playgroud)

它完成了。