使用 Laravel 模型更新表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35279933/
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
Update Table Using Laravel Model
提问by danjswade
I've got a table for a sports team. The record shows the team selection and some other information. I want to update the record with the team selection. My model is thus:
我有一个运动队的桌子。该记录显示了团队选择和其他一些信息。我想用团队选择更新记录。我的模型是这样的:
class Selection extends Model {
protected $table = "selection";
protected $fillable = [
'loose',
'hooker',
'tight',
'secrow1',
'secrow2',
'blindflank',
'openflank',
'eight',
'scrum',
'fly',
'leftwing',
'rightwing',
'fullback',
'sub1',
'sub2',
'sub3',
'sub4',
'sub5'
];
}
}
So I have a form which gives all the data for the positions and gives the id for the record in the DB. In my controller, I've got:
所以我有一个表格,它提供了职位的所有数据,并提供了数据库中记录的 id。在我的控制器中,我有:
public function storeFirstTeam()
{
$input = Request::all();
Selection::update($input->id,$input);
return redirect('first-team');
}
But I get the following error:
但我收到以下错误:
Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically, assuming $this from incompatible context
非静态方法 Illuminate\Database\Eloquent\Model::update() 不应静态调用,假设 $this 来自不兼容的上下文
Can anyone point out my silly error?
谁能指出我的愚蠢错误?
回答by Jilson Thomas
Please check the code below and this would solve your problem:
请检查下面的代码,这将解决您的问题:
Selection::whereId($id)->update($request->all());
回答by Martin Bean
The error message tells you everything you know: you're trying to call a method statically (using the double colons) that isn't meant to be.
错误消息告诉你你知道的一切:你试图静态地调用一个不应该的方法(使用双冒号)。
The update()
method is meant to be called on a model instance, so first you need to retrieve one:
该update()
方法旨在在模型实例上调用,因此首先您需要检索一个:
$selection = Selection::find($id);
You can then can the update()
method on that:
然后,您可以使用该update()
方法:
$selection->update($request->all());
回答by The Alpha
You should write it like given example below:
您应该像下面给出的示例一样编写它:
Selection::where('id', $input['id'])->update($input);
// Or use this using dynamic where
Selection::whereId($input['id'])->update($input);
Alternatively, you may write it like this as well:
或者,你也可以这样写:
Selection::find($input['id'])->fill($input)->save();