php 调用未定义的方法 Illuminate\Database\Query\Builder::save()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24023516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to undefined method Illuminate\Database\Query\Builder::save()
提问by Malchesador
I am trying to call Eloquent's save() method on an existing record but getting an error from Illuminate's Query Builder.
我试图在现有记录上调用 Eloquent 的 save() 方法,但从 Illuminate 的查询生成器中收到错误。
Following the documentation on Laravel's web site at http://laravel.com/docs/eloquent#insert-update-deletefor 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.
按照 Laravel 网站http://laravel.com/docs/eloquent#insert-update-delete上的文档更新检索到的模型,并查看此处的示例:Laravel Eloquent ORM save: update vs create, my code似乎遵循预期的约定,但我收到了这篇文章标题中提到的错误。
$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?
Employee 类扩展了 Eloquent,如果我创建模型的新实例,然后设置一些属性,然后调用 save() 方法,它会很好地执行插入语句。我错过了什么?
回答by Malchesador
Apparently the ->get()
method will not work with Eloquent's ->save()
method and you must use ->first()
instead.
显然,该->get()
方法不适用于 Eloquent 的->save()
方法,您必须->first()
改用。
Correct:$this->employee = Employee::where('login', $login)->first();
正确的:$this->employee = Employee::where('login', $login)->first();
Incorrect:$this->employee = Employee::where('login', $login)->get();
不正确:$this->employee = Employee::where('login', $login)->get();
See http://laravel.io/forum/06-04-2014-symfony-component-debug-exception-fatalerrorexception-call-to-undefined-method-illuminatedatabaseeloquentcollectionsavefor additional reference.
回答by EselDompteur
you have to fetch your model after given an ->where
你必须在给定 -> 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()
如果你不这样做,你的对象 $this->employee 就不是一个,你不能使用 ->save()