据我理解,您的问题可以通过模型事件和当前模型以及关联模型的某些额外代码来实现。
Laravel模型事件
如果您不想使用任何额外的东西,只需使用Laravel模型事件(实际上Ardent正在包装这些钩子)。请查看文档
http://laravel.com/docs/5.1/eloquent#events
引用:
Eloquent模型触发多个事件,允许您使用以下方法钩入模型生命周期中的各个点:creating、created、updating、updated、saving、saved、deleting、deleted、restoring、restored。
每当第一次保存新项目时,将触发创建和创建事件。如果项目不是新项目并且调用了保存方法,则将触发更新/更新事件。在这两种情况下,将触发保存/保存事件。
如果从创建、更新、保存或删除事件返回false,则操作将被取消。
最后,关于你的问题,你可以以多种方式利用上述方法,但最明显的是你可以将它与Eloquent模型的
getDirty() api docs here方法和
getRelation() api docs here方法结合使用(或不结合)。例如,在保存事件中使用它。
Model::saving(function($model){
foreach($model->getDirty() as $attribute => $value){
$original= $model->getOriginal($attribute);
echo "Changed";
}
$relations = $model->getRelations();
foreach($relations as $relation){
$relation_model = getRelation($relation);
foreach($relation_model->getDirty() as $attribute => $value){
$original= $relation_model->getOriginal($attribute);
echo "Relation Changed";
}
}
return true;
});
另一个想法可能会对您有所帮助。当您保存时
save()
将检查模型中是否有更改。如果没有更改,它不会运行数据库查询。
这是Illuminate\Database\Eloquent\Model@performUpdate
中相关的代码部分:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
}
return true;
}
getDirty()
方法仅在模型创建时,将当前属性与保存在 original
中的副本进行比较。这是在 syncOriginal()
方法中完成的:
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
检查模型是否有更改 isDirty()
:
if($user->isDirty()){
// changes have been made
}
或检查特定属性:
if($user->isDirty('price')){
}
我没有检查过这段代码,但希望能够作为您的答案使用。如果您在处理此要求或需要优化或更改某些内容时有任何疑问,请告诉我。
->relations
来检查它的关联模型。 - Safoor Safdar