【发布时间】:2015-07-29 19:24:51
【问题描述】:
在使用 Laravel 5.1 时,我正在尝试创建一个会自动更新以下 3 列的观察者
- created_by:当创建的记录“不再更新”时填充
- modified_by:每次修改记录时填充一个新值
- purged_by:软删除记录时填充一个值。
我了解 Eloquent 会自动更新日期时间戳(created_by、updated_at、removed_at),但我需要更新进行更改的 user_id。
有人建议我使用 Observer 和 trait 来处理这个问题。这是我所做的
1) 在app\Observers\ModelSignature.php 中创建了一个名为“ModelSignature”的观察者类,这就是它的内容
<?php
namespace App\Observers;
class ModelSignature {
protected $userID;
public function __construct(){
$this->userID = Auth::id();
}
public function updating($model)
{
$model->modified_by = $this->userID;
}
public function creating($model)
{
$model->created_by = $this->userID;
}
public function removing($model)
{
$model->purged_by = $this->userID;
}
}
然后我创建了一个名为“RecordSignature”的新特征,位于app\Traits\RecordSignature.php,并包含以下代码
<?php
namespace App\Traits;
use app\Observers\ModelSignature;
trait RecordSignature
{
public static function bootObservantTrait()
{
static::observe(new ModelSignature() );
}
}
最后,在位于“app\Models\Account.php”的“帐户”模型中,我像这样使用它
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\industry;
use App\Traits\RecordSignature;
use App\Traits\TrimScalarValues;
class Account extends Model
{
use RecordSignature, TrimScalarValues;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'accounts';
protected $primaryKey = 'account_id';
const CREATED_AT = 'created_on';
const UPDATED_AT = 'modified_on';
const REMOVED_AT = 'purged_on';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['client_id','account_name', 'company_code', 'legal_name', 'created_by','modified_by','instrucations'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
//protected $hidden = ['account_id', 'remember_token'];
protected $guarded = ['account_id'];
/**
* Get the industry record associated with the account.
*/
public function industry()
{
return $this->hasOne(industry, industry::primaryKey);
}
public function pk(){
return $this->primaryKey;
}
}
问题在于 updating()、removing() 和 creating() 方法没有按预期填充 userId。似乎字段被忽略或方法没有被触发!
我在这里做错了什么?
【问题讨论】:
-
你订阅了 Laracasts 吗?
-
你需要为此创建引导
标签: php laravel laravel-5 traits