Laravel更新后返回旧模型

efzxgjgh  于 2023-06-24  发布在  其他
关注(0)|答案(2)|浏览(162)

当我存储新记录时,Laravel会返回新记录。一切正常。当我更新记录时,Laravel会返回旧记录。我想归还更新的记录。
控制器

public function store(StoreProjectRequest $request)
    {
        $data = $this->repo->create( $request->all());

        return response()->json(new ProjectResource($data));
    }

    public function update(UpdateProjectRequest $request, Project $project)
    {
        $data = $this->repo->update($project, $request->all());

        return response()->json(new ProjectResource($data));
    }

仓库

public function create( $data)
    {
        $this->model->name = $data['name'];
        $this->model->description = $data['description'];
        $this->model->sales_order_id = $data['sales_order_id'] ? $data['sales_order_id'] : NULL;
        $this->model->project_leader_id = $data['project_leader_id'];
        $this->model->project_type_id = $data['project_type_id'];
        $this->model->project_status_id = $data['project_status_id'];
        $this->model->creator_id = Auth()->id();
        $this->model->save();

        return $this->model;
    }

    public function update($model, $data)
    {
        $model->name = $data['name'];
        $model->description = $data['description'];
        $model->sales_order_id = $data['sales_order_id'];
        $model->project_leader_id = $data['project_leader_id'];
        $model->project_type_id = $data['project_type_id'];
        $model->project_status_id = $data['project_status_id'];
        $model->save();

        return $model;
    }

当我添加$data = Project::find($project->id)时,我会收到更新的模型。
但这是唯一的办法吗?

ryevplcw

ryevplcw1#

如果您已经有一个从数据库中检索到的Eloquent模型示例,那么您可以使用fresh和refresh方法“刷新”模型
Laravel文件
fresh方法将从数据库中重新检索模型。现有模型示例将不受影响
刷新方法将使用来自数据库的新数据对现有模型进行再水合。此外,它的所有加载关系也将被刷新

xriantvc

xriantvc2#

$data作为旧数据返回的原因是因为它仍然存储变量创建时的数据。当你调用$data->fresh()时,它会获取新的数据并返回。这有道理吗

相关问题