Call to undefined method Illuminate\Database\Query\Builder::save()

做~自己de王妃 提交于 2019-12-04 16:45:34

问题


I am trying to call Eloquent's save() method on an existing record but getting an error from Illuminate's Query Builder.

Following the documentation on Laravel's web site at http://laravel.com/docs/eloquent#insert-update-delete for updating a retrieved model, and also looking at the example here: Laravel Eloquent ORM save: update vs create, my code appears to follow the expected convention, but instead I get the error mentioned in the title of this post.

$this->employee                  = Employee::where('login', $login);
$this->employee->first_name         = 'John';
$this->employee->last_name          = 'Doe';
$this->employee->save();

The Employee class extends Eloquent, and if I create a new instance of the model and then set some attributes and then call the save() method it performs the insert statements just fine. What am I missing?


回答1:


Apparently the ->get() method will not work with Eloquent's ->save() method and you must use ->first() instead.

Correct: $this->employee = Employee::where('login', $login)->first();

Incorrect: $this->employee = Employee::where('login', $login)->get();

See http://laravel.io/forum/06-04-2014-symfony-component-debug-exception-fatalerrorexception-call-to-undefined-method-illuminatedatabaseeloquentcollectionsave for additional reference.




回答2:


you have to fetch your model after given an ->where

$this->employee = Employee::where('login', $login)->get();

or

$this->employee = Employee::where('login', $login)->first();

if you don't do that your Object $this->employee would't be one and you could not use ->save()



来源:https://stackoverflow.com/questions/24023516/call-to-undefined-method-illuminate-database-query-buildersave

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!