Laravel资源追加本地修改的属性

我想在将本地更改附加到模型中已经存在的某些属性(以不更改数据库值的方式)的同时返回模型的资源。实现此目的的正确方法是什么(因为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 same keys but MAYBE different values

$localized= $this->localize($model);

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;
    

    As long as you don't call save() on $model later on, the database won't be affected.