每次从数据库检索我的人员对象,然后再次保存时,我都需要更新它。但是该怎么做呢?
我的对象 Person 的 bool 属性 saw_by_organization 在创建时为 0。 第一次从数据库检索 Person 时,我想将 saw_by_organization 设置为 1。
我尝试将其放入构造函数中,但似乎不起作用
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
if($this->seen_by_organization == 0)
{
$this->seen_by_organization = 1;
$this->save();
}
}
我知道一种将代码绑定(bind)到“保存时”的方法,但不知道“获取之前”或“获取之后”。
protected static function boot()
{
parent::boot();
//This is on saving
static::saving(function($model)
{
});
//Is there something like this ?
static::getting(function($model)
{
}
}
希望你能帮助我
谢谢!
最佳答案
没有为此的内置事件。另外,created
并不是您需要的 - 当新模型插入存储时它会被触发。
你需要这样的东西:
// This is called after fetching data from db
// override it in order to fire the event you need
public function setRawAttributes(array $attributes, $sync = false)
{
parent::setRawAttributes($attributes, $sync);
$this->fireModelEvent('loaded', false);
}
// add handler for new event
public static function loaded($callback)
{
static::registerModelEvent('loaded', $callback);
}
// do the job
public static function boot()
{
parent::boot();
static::loaded(function ($user) {
if($user->exists && $user->seen_by_organization == 0)
{
$user->seen_by_organization = 1;
$user->save();
}
});
}
请注意,您使用 get()
或 first()
等检索的每个模型都会调用它,因此可能有多个插入
.
关于php - 在 Laravel 中扩展模型获取/构建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25422744/