Laravel:在使用Query Builder或Eloquent ORM时,在每次插入/更新时执行一些任务

rgv*_*ley 6 php query-builder laravel eloquent laravel-4

问题

我想自动添加created_bymodified_by字段到Laravel 4中数据库表的每次插入/更新,无论我使用的是Eloquent还是Query Builder.但是,并非所有表都包含这些字段,因此任何解决方案都必须在添加之前检查这些列是否存在.

试图解决方案

我已经扩展了Illuminate\Database\Eloquent\Model类并编写了一个覆盖方法save(),以便为每个保存的记录添加一些额外的元数据字段.

这很好,除非我使用查询生成器执行插入,然后绕过它.看一下这个Model类,看起来数据库操作实际上是使用查询构建器完成的.

我看过Illuminate\Database\Query\Builder模型,看起来我可能会为insert()和编写覆盖方法update().

这是为每次插入/更新执行某项任务的合理方式,还是在以后遇到麻烦?

小智 8

添加到上面的答案.你可以这样做.

在app/models中创建一个名为BaseModel.php的类,扩展\ Eloquent

class BaseModel extends \Eloquent{

public static function boot()
{
    parent::boot();

    static::creating(function($model)
    {
        //change to Auth::user() if you are using the default auth provider
        $user = Confide::user();
        $model->created_by = $user->id;
        $model->updated_by = $user->id;
    });

    static::updating(function($model)
    {
        //change to Auth::user() if you are using the default auth provider
        $user = Confide::user();
        $model->updated_by = $user->id;
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

然后在您的单个模型类中,您需要扩展BaseModel而不是\ Eloquent

class Product extends BaseModel {

    protected $table = 'product';

    //Booting the base model to add created_by and updated_by to all tables
    public static function boot()
    {
        parent::boot();
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,只要保存或更新模型,created_by和updated_by字段就会自动更新.

注意:这仅在通过Eloquent完成保存或更新时才有效.对于查询构建器,您可以使用常用方法来获取并附加created_by和update_by列更新.


Atr*_*eur 7

您必须永远不要覆盖保存方法以覆盖并添加您的功能.

您必须使用雄辩提供的模型事件功能,而不是这样做.

简而言之,您必须为模型定义一个保存事件,以覆盖/设置/检查模型将要保存的数据.

放入User模型类的一个简单示例:

//Executed when loading model
public static function boot()
{
     parent::boot();

     User::creating(function($user){
         $user->value1 = $user->value2 +1;
     });
}
Run Code Online (Sandbox Code Playgroud)

更多信息:http: //four.laravel.com/docs/eloquent#model-events


ruw*_*800 5

在 Laravel 中,如果您想从单个点在每次保存/更新时调用单个方法,而不在每个扩展 Model 中进行任何其他更改,您可以为 eloquent 事件创建一个自定义侦听器。正如文档所说,它只能针对每个模型完成。但是创建自定义侦听器允许访问任何模型中的任何事件。

只需向如下boot()方法添加一个侦听器并进行相应修改即可。EventServiceProvider

Event::listen(['eloquent.saving: *', 'eloquent.creating: *'], function($event){
        //your method content
        //returning false will cancel saving the model
 });
Run Code Online (Sandbox Code Playgroud)

请注意,通配符用于匹配任何模型。有关事件的更多信息,请参阅文档。