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

时间:2014-08-26 09:58:50

标签: laravel laravel-4 eloquent

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

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

我使用laravel 4.2.8&口才

4 个答案:

答案 0 :(得分: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'));
}

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

// 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

答案 1 :(得分:3)

这样的事情是要走的路:

// 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();

已经完成了。

答案 2 :(得分:1)

我宁愿使用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();

答案 3 :(得分:1)

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

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

    return parent::delete();
}

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