Laravel Resource附加本地修改的属性



我想返回模型的Resource,同时将局部更改附加到模型中已经存在的一些属性(以不更改数据库值的方式(。为了实现这一点,正确的调用方法是什么(因为append函数不正确(?

// exists $model->currency
// Version: Laravel 7.x
// ModelResoruce is a Illuminate/Http/JsonResource
$tempCurrency = $this->findCurrecy($model->currency);
return ok(ModelResource::make($model)->append(['currency' => $tempCurrency, /* multiple dynamic changes*/]);
// updated: more real scenario:
// $localized has MANY dynamic keys that exist in model but MAYBE different values
$localized= ['currency' => 'x', 'name' => 'y',]; 

ok(ModelResource::make($model)->append($localized);
// I want: user will see temp but data is not modified
// What happens: append does not change currency's value

这不会修改数据库:

$tempCurrency = $this->findCurrecy($model->currency);
$model->currency = $tempCurrency;

只要以后不在$model上调用save(),数据库就不会受到影响。

最新更新