我想更新或创建模型。它根本不起作用。
这是我的代码:
foreach ($ProfileRequest as $fieldname => $value){
ProfileRequest::updateOrCreate(['sm_id' => $uid, 'field_name' => $fieldname],
[
'sm_id' => $uid,
'field_name' => $fieldname,
'value' => $value
]);
}
这适用于插入:
foreach ($ProfileRequest as $fieldname => $value) {
$req = new ProfileRequest;
$req->chef_id = $uid;
$req->field_name = $fieldname;
$req->value = $value;
$req->save();
}
答案 0 :(得分:5)
您需要在模型中指定可填写字段,因为您正在处理批量更新。把它放在你的模特
protected $fillable = ['field_name','value'];
答案 1 :(得分:0)
像这样更改你的代码
foreach ($ProfileRequest as $fieldname => $value){
ProfileRequest::updateOrCreate(
[
'sm_id' => $uid
],
[
'field_name' => $fieldname,
'value' => $value
]
);
}
避免重复这些字段。如果以某种方式,我的代码不适合您,请在此处查看自己的函数定义:https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_updateOrCreate
答案 2 :(得分:-2)
这有效
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();
}