我正在使用laravel updateOrCreate函数
$variable = Variable::updateOrCreate(
['name' => $name,
'landing_id' => $landing_id,
'version_id' => $version_id,
'page_id' => $page_id],
[
'user_id' => Auth::user()->id
'user_modified_id' => Auth::user()->id ]
);
如何正确使用此功能,在创建记录时为user_id添加值,当记录更新时,user_modified_id将被更新。
Well i found work around for my issue but i don't know if this is best way to do. What i have to do is this:
if( $variable->user_id == 0){
$variable->user_id = Auth::user()->id;
}
$variable->value = $setting;
$variable->save();
答案 0 :(得分:0)
您可以使用以下代码执行数据。第一个表示匹配的条件,第二个表示要更新的字段。
$variable = Variable::updateOrCreate([
//Add unique field combo to match here
//For example, perhaps you only want one entry per user:
'user_id' => Auth::user()->id,
],[
'name' => $name,
'landing_id' => $landing_id,
'version_id' => $version_id,
'page_id' => $page_id
]);
这种方式肯定更好。
答案 1 :(得分:0)
$variable = Variable::updateOrCreate(
['name' => $name,
'landing_id' => $landing_id,
'version_id' => $version_id,
'page_id' => $page_id],
'user_id' => Auth::user()->id
[
'user_modified_id' => Auth::user()->id ]
);
如果没有匹配,第一个数组将创建一个新模型,如果存在,第二个数组将更新指定的值。
您的问题是,如果没有匹配的记录,user_modified_id
将与user_id
一起创建。