如何知道 laravel 模型值是否在保存回调时更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23108361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to know if laravel model values changed on save callback
提问by abbood
following thisanswer, I do model save callbacks (similar to rails) in Laravel like so:
按照这个答案,我在 Laravel 中做模型保存回调(类似于 rails),如下所示:
class LessonPlan extends Eloquent {
public function save(array $options = array())
{
// before save code
parent::save();
// after save code
}
}
However, I call save() on Page
when i'm saving a newpage or updating an existingone. How do I know which is which in this operation?
但是,Page
当我保存新页面或更新现有页面时,我会调用 save() 。我怎么知道在这个操作中哪个是哪个?
I tried something like
我试过类似的东西
public function save(array $options = array())
{
// before save code
$oldLesson = clone $this;
parent::save();
..
if ($this->isLessonStatusChanged($oldLesson)) {
..
}
}
private function isLessonStatusChanged($oldLesson) {
return $this->status != $oldLesson->status;
}
but that's no good.. since $oldLesson will already have the new values of $lesson
但这不好.. 因为 $oldLesson 已经拥有 $lesson 的新值
what I ended up doing was simply regexing the url to see if it's an update request.. but I'm already having trouble sleeping at night (my answer doesn't really tell me if any values have actually changed.. b/c one can submit an update form without actually changing anything).. is there a cleaner way of doing this?
我最终做的只是对 url 进行正则表达式以查看它是否是更新请求..可以在不实际更改任何内容的情况下提交更新表单).. 有没有更简洁的方法来做到这一点?
回答by afarazit
You can use the isDirty()
method which returns a bool
and getDirty()
which returns an array
with the changed values.
您可以使用isDirty()
返回 abool
并getDirty()
返回array
具有更改值的an的方法。
public function save(array $options = array())
{
$changed = $this->isDirty() ? $this->getDirty() : false;
// before save code
parent::save();
// Do stuff here
if($changed)
{
foreach($changed as $attr)
{
// My logic
}
}
}
回答by nvisser
Have you tried Model::getDirty()
? I haven't tried it myself but it returns the attributes that have changed since the last sync. See the API docs.
你试过Model::getDirty()
吗?我自己没有尝试过,但它返回自上次同步以来已更改的属性。请参阅 API 文档。