更新具有已修改主键的条目时,Laravel 5.5方法保存不存在

时间:2017-10-23 08:24:32

标签: php laravel-5 laravel-5.5

我正在使用laravel 5.5来更新条目。问题是在更改主键'id'之后,这是一个默认的默认pk为'project_id'。添加项目工作正常,但更新项目不能正常工作。这是我得到的错误。

  

方法保存不存在。

这是我的模特。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
   protected $primaryKey = 'project_id';
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function tasks()
    {
        return $this->hasMany(Task::class);
    }
}

这是我的控制器功能。

public function editProject($id){

        $project = Project::where('project_id', $id)->firstOrFail();
        $data = ["project_info" => $project];
        return view('projects.edit')->with($data);
    }
    public function updateProject(Request $request){
        $data = $request->all();
        $validator = Validator::make($data, [
            'project_title' => 'required',
            'project_description' => 'required',
            'project_start_date' => 'required',
            'project_end_date' => 'required',
            'project_status' => 'required',
        ]);

        $response = [];

        if ($validator->fails()){
            $response["errors"] = [$validator->messages()->first()];
            $response["success"] = false;
            return json_encode($response);
        }

        else{
            $project = Project::where("project_id", $request->input('project_id'))->get();
            $project->project_title = $request->project_title;
            $project->user_id = Session::get('user_id');
            $project->project_description = $request->project_description;
            $project->project_start_date = $request->project_start_date;
            $project->project_end_date = $request->project_end_date;
            $project->project_status = $request->project_status;
            $project->save();
            return redirect('/listProjects');
        }
    }

3 个答案:

答案 0 :(得分:21)

使用get()会返回collection。尽管您传递了一个“唯一”ID project_id,它仍将返回一个集合 - 该集合中只有一个元素。

随后,您的代码将无法按照您的经验运行,或者至少在没有一些更改的情况下使$project引用集合中的第一个元素。

这是一个快速解决方案,只需改变这个:

$project = Project::where("project_id", $request->input('project_id'))->get();

到此:

$project = Project::where("project_id", $request->input('project_id'))->first();

通过使用first(),eloquent将返回与查询匹配的第一个元素并实际返回元素(而不是具有一个元素的集合),因此您可以直接编辑并保存它。

答案 1 :(得分:1)

这是我找到的解决方案。

$project_id = $request->input('project_id');
$project = Project::find($project_id);
$project->save();

答案 2 :(得分:1)

您可以使用ID通过ID查找它

Project::find($id);

或者像詹姆斯所说的那样获得第一个元素:

$project = Project::where("project_id", $request->input('project_id'))->first();