在发送响应之前修改模型数据

Modifying model data before sending response

我正在开发一个后端,需要根据用户特定的货币重新计算价格。

我从数据库中获取所有需要的记录如下:

 $tasks = Task::with([
            'images' => function($query){},
            'price' => function($query){},
            'user' => function($query){ $query->with('images');},
        ])->whereDoesntHave('tasksState', function($query) use ($user){
            $query->where('user_id', $user->id);
            $query->where('state', '<>', 0);
        })->where('id', '>', $offset)->where('user_id', '<>', $user->id)->take($limit)->get();

任务的价格模型由货币和价值属性组成。

然后我遍历 $tasks 并根据用户特定的货币重新计算价格:

foreach ($tasks as $k => $task){
            $price = $task->price->value;
            $price = $price * $rate->getValue();
            $tasks[$k]->price = $price;
            //$task->price = $price;
        }

检查任务后,所有价格重新计算正确。

然而,当我随后序列化 $tasks 并将其作为响应发送时,它包含从数据库中获取的数据——没有重新计算价格。

有没有人哪里出了问题?任何想法将不胜感激!

由于无论如何都要对数据进行序列化,因此 can first convert collection into an array 并将其作为数组处理:

$tasks->toArray();

在这种情况下,您将能够覆盖原始数据,就像您尝试使用 foreach 循环完成的那样。

作为替代方案,您可以 create a mutator 这会将 calculated_price 属性 添加到集合中。

您可以为此使用 Eloquent Mutator

Task 模型中创建以下函数

public function getNewPriceAttribute($value)
{
  ...// do your processing here
}

然后您可以将其用作:

$task->new_price;

创建访问器后,将属性名称添加到 Task 模型上的 appends 属性。

 protected $appends = ['new_price'];

将属性添加到追加列表后,它将同时包含在模型的数组和 JSON 表示中。