Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

php - Laravel: performing some task on every insert/update when using Query Builder or Eloquent ORM

The Problem

I would like to automatically add created_by and modified_by fields to every insert/update to a database table in Laravel 4, regardless of whether I am using Eloquent or Query Builder. However, not all my tables have these fields so any solution will have to check these columns exist before adding.

Attempted Solution

I have extended the IlluminateDatabaseEloquentModel class and written an overwrite method save() in order to add some additional meta data fields for every record that is saved.

This is fine except that if I perform an insert using the Query Builder then this is bypassed. Looking at the Model class it appears that the database operations are actually done using the query builder.

I have had a look at the IlluminateDatabaseQueryBuilder model and it looks like I could probably write overwrite methods for insert() and update().

Is this a sensible way to go about performing some task for every insert/update or will I run into trouble later down the line?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding to the above answers. You could do something like this.

Create a class in app/models called BaseModel.php extending 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;
    });
  }

}

Then in your individual model classes you need to extent the BaseModel instead of 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();
    }

}

Now any time you save or update a model, the created_by and updated_by fields would be updated automatically.

Note: This would only work when save or update is done through Eloquent. For query builder, you could have a common method to fetch and append the created_by and update_by column updates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...