Laravel 5.6 - 在 updateOrCreate 后获取更改的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51028944/
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
Laravel 5.6 - get changed values after updateOrCreate
提问by menasoft
I have used laravel 5.6 and used the updateOrCreate
model to add or update some data.
But I need to get all the values which changed
我使用了 laravel 5.6 并使用该updateOrCreate
模型添加或更新了一些数据。
但我需要得到所有改变的值
$q=Userssub::updateOrCreate(
['userid' => $uid ],
['model' => $model]
);
and the result shows like in this image
结果如下图所示
How can I get the changes array?
I tried to get it with
如何获取更改数组?
我试着用
$u->changes
and
和
$u->changes->toarray()
but both return null.
What can I do to get the changed values?
但两者都返回空值。
我该怎么做才能获得更改后的值?
回答by DigitalDrifter
Eloquent models have two protected arrays, $original
and $changes
, which contain the attributes as they were when fetched from storage and the attrbirutes which have been modified, respectively.
Eloquent 模型有两个受保护的数组$original
和$changes
,它们分别包含从存储中获取时的属性和已修改的属性。
So you can use getOriginal()
and getChanges()
and compare the differences.
所以,你可以用getOriginal()
和getChanges()
和比较的差异。
$model = Model::createOrUpdate([...]);
// wasRecentlyCreated is a boolean indicating if the model was inserted during the current request lifecycle.
if (!$model->wasRecentlyCreated) {
$changes = $model->getChanges();
}
回答by stardust4891
This creates an array which will contain the original attribute value and what it was changed to:
这将创建一个包含原始属性值及其更改内容的数组:
if (!$model->wasRecentlyCreated) {
$original = $model->getOriginal();
$changes = [];
foreach ($model->getChanges() as $key => $value) {
$changes[$key] = [
'original' => $original[$key],
'changes' => $value,
];
}
}
e.g.
例如
(
[first_name] => [
[original] => Kevinn
[changes] => Kevin
]
[website] => [
[original] => google.com
[changes] => google.ca
]
)