updateOrCreate 在 Laravel Eloquent 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42505094/
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
updateOrCreate does not work in Laravel Eloquent
提问by Manish Jakhmola
I want to update or create a model. It's not working at all.
我想更新或创建模型。它根本不起作用。
Here is my code:
这是我的代码:
foreach ($ProfileRequest as $fieldname => $value){
ProfileRequest::updateOrCreate(['sm_id' => $uid, 'field_name' => $fieldname],
[
'sm_id' => $uid,
'field_name' => $fieldname,
'value' => $value
]);
}
This is working for insertion:
这适用于插入:
foreach ($ProfileRequest as $fieldname => $value) {
$req = new ProfileRequest;
$req->chef_id = $uid;
$req->field_name = $fieldname;
$req->value = $value;
$req->save();
}
回答by redfades
You need to specify the fillable fields in your model since you are dealing with Mass Updates. Put this at your model
由于您正在处理批量更新,因此您需要在模型中指定可填写的字段。把这个放在你的模型上
protected $fillable = ['field_name','value'];
回答by EddyTheDove
Change your code like this
像这样改变你的代码
foreach ($ProfileRequest as $fieldname => $value){
ProfileRequest::updateOrCreate(
[
'sm_id' => $uid
],
[
'field_name' => $fieldname,
'value' => $value
]
);
}
Avoid repeating the fields. If somehow, my code doesn't work for you, please go check the function definition for yourself here: https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_updateOrCreate
避免重复字段。如果不知何故,我的代码对您不起作用,请在此处自行检查函数定义:https: //laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_updateOrCreate
回答by Manish Jakhmola
This works
这有效
foreach ($ProfileRequest as $fieldname => $value){
ProfileRequest::firstOrNew(array('sm_id' => $uid, 'field_name' => $fieldname));
$chefReq->sm_id = $uid;
$chefReq->field_name = $fieldname;
$chefReq->value = $value;
$chefReq->save();
}