在 laravel 5.4 中更新查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45276385/
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 Query in laravel 5.4
提问by Manjunath A M
How can I update multiple rows
如何更新多行
I'm getting below array
我低于阵列
[
"3",
"4",
"5"
]
My Controller
我的控制器
$answers= $request->get('option'); //answers array
foreach ($answers as $answer)
{
Answer::where('question_id', 1)->update(
['customer_id' => 1,
'answer' => $answer]);
}
采纳答案by Alexey Mezenin
You can use update()
method:
您可以使用update()
方法:
Answer::where('question_id', 2)->update(['customer_id' => 1, 'answer' => 2]);
The update method expects an array of column and value pairs representing the columns that should be updated
update 方法需要一个列和值对数组,表示应该更新的列
Don't forget to add customer_id
, answer
to the $fillable
array:
不要忘记将customer_id
,添加answer
到$fillable
数组中:
protected $fillable = ['customer_id', 'answer'];
回答by Margi
If you are using query builder then use bellow query
如果您使用的是查询构建器,则使用波纹管查询
DB::table('answers')
->where('question_id', 2)
->update(array('customer_id' => 1, 'answer' => 2]);
and if you are using Eloquent ORM then use bellow query
如果您使用的是 Eloquent ORM,则使用波纹管查询
App\Answers::where('question_id', 2)->update(['customer_id' => 1,'answer'=>2]);
回答by Sagar Gautam
You can update with simple following query.
您可以使用简单的以下查询进行更新。
DB::table('answers')->where('id',2)->update(['customer_id' => 1, 'answer' => 2]);
It's better to use Eloquent Model like,
最好使用 Eloquent 模型,例如,
Answer::where('id',2)->update(['customer_id' => 1, 'answer' => 2]);
If you have not added these column in $fillable
property of model then, you can update with after find like,
如果您还没有在$fillable
模型的属性中添加这些列,则可以在查找后更新,例如,
$answer = Answer::find(2);
$answer->customer_id = 1;
$answer->answer = 2;
$answer->save();
Hope you understand.
希望你能理解。