問題描述
我想在 Laravel 4 中每次插入/更新數據庫表時自動添加 created_by
和 modified_by
字段,無論我使用的是 Eloquent 還是 Query Builder.但是,并非我所有的表都有這些字段,因此任何解決方案都必須在添加之前檢查這些列是否存在.
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.
我已經擴展了 IlluminateDatabaseEloquentModel
類并編寫了一個覆蓋方法 save()
以便為每個保存的記錄添加一些額外的元數據字段.
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.
這很好,只是如果我使用查詢生成器執行插入,則會被繞過.查看 Model
類,似乎數據庫操作實際上是使用查詢構建器完成的.
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.
我看過IlluminateDatabaseQueryBuilder
模型,看起來我可以為 insert()
和 update()
編寫覆蓋方法.
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?
推薦答案
添加到上述答案中.你可以做這樣的事情.
Adding to the above answers. You could do something like this.
在應用程序/模型中創建一個名為 BaseModel.php 擴展 Eloquent 的類
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;
});
}
}
然后在您的各個模型類中,您需要擴展 BaseModel 而不是 Eloquent
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();
}
}
現在,無論何時保存或更新模型,created_by 和 updated_by 字段都會自動更新.
Now any time you save or update a model, the created_by and updated_by fields would be updated automatically.
注意:這僅在通過 Eloquent 完成保存或更新時有效.對于查詢構建器,您可以使用通用方法來獲取和附加 created_by 和 update_by 列更新.
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.
這篇關于Laravel:在使用查詢生成器或 Eloquent ORM 時在每次插入/更新時執行一些任務的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!