Laravel 更新或创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50716637/
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
Laravel UpdateOrCreate
提问by Ruka Xing
I'm trying to if there are records just update and if there are not records just create. Problem is:
我正在尝试是否有记录只是更新,如果没有记录只是创建。问题是:
Already has records case: It creates records when there are already have record in database.
已有记录的情况:当数据库中已有记录时创建记录。
public function store(Request $request)
{
$time = $request->input('time');
foreach ($request->input('number') as $key => $value) {
Choice::UpdateOrCreate([
'user_id' => Auth::id(),
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
}
回答by Saurabh Mistry
use this way :
使用这种方式:
$matchThese=array('user_id' => Auth::id())
Choice::updateOrCreate($matchThese,['topic_id'=>$key,'question_number' => $value,'time' => $time]);
回答by Maraboc
You have to pass two parameters to the UpdateOrCreate
the first is the attributes
of searching records the second is the values
in the doc of the method we have :
您必须将两个参数传递给第UpdateOrCreate
一个是attributes
搜索记录的,第二个是values
在我们拥有的方法的文档中:
Create or update a record matching the attributes, and fill it with values.
创建或更新与属性匹配的记录,并用值填充它。
So if you search the record just with the user_id
you have to do it like this :
因此,如果您仅使用 搜索记录,则user_id
必须这样做:
public function store(Request $request)
{
$time = $request->input('time');
foreach ($request->input('number') as $key => $value) {
Choice::UpdateOrCreate([
'user_id' => Auth::id()
],
[
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
}
回答by piyush
As per Rest Update in crud UpdateOrCreatecreates a record if it doesn't finds a matching record. So, you format of Choice::UpdateOrCreate must be like this
根据 crud UpdateOrCreate 中的Rest Update,如果未找到匹配的记录,则会创建一条记录。所以,你的 Choice::UpdateOrCreate 格式必须是这样的
Choice::updateOrCreate(['user_id' => Auth::id(),
'time' => $time,], [
'topic_id' => $key,
'question_number' => $value,
])
where ['user_id' => Auth::id(), 'time' => $time,] is the check for existance of a record.
其中 ['user_id' => Auth::id(), 'time' => $time,] 是检查记录是否存在。
回答by thefallen
Try replacing the code in the loop with this:
尝试用以下代码替换循环中的代码:
...
Choice::UpdateOrCreate(
['user_id' => Auth::id(), 'time' => $time],
['topic_id' => $key, 'question_number' => $value]
);
...
This will search for a record of user at specific time and create one if there is not, but if there is it will update its topic_id and question_number.
这将在特定时间搜索用户的记录,如果没有则创建一个,但如果有,它将更新其 topic_id 和 question_number。