[英]Trying to understand how to make a UpdateOrCreate
I have a model with the following code:我有一个 model ,代码如下:
public static function insertSent($itemId, $currentPackId)
{
$itemHistory = new ItemHistory([
'item_id' => $itemId,
'pack_id' => $currentPackId,
'status' => self::SENT,
'returned_by' => Auth::id()
]);
$itemHistory->save();
}
public static function insertReturned($itemId, $currentPackId)
{
$itemHistory = new ItemHistory([
'item_id' => $itemId,
'pack_id' => $currentPackId,
'status' => self::RETURNED,
'returned_by' => Auth::id()
]);
$itemHistory->save();
}
I just added the insertSent and I want to change the insertReturned to a function where it updates a record if it exists or creates it so UpdateOrCreate.我刚刚添加了 insertSent,我想将 insertReturned 更改为 function,如果它存在则更新记录或创建它,以便 UpdateOrCreate。
I'm using laravel php我正在使用 laravel php
You can adjust your method to use updateOrCreate
pretty easily:您可以很容易地调整您的方法以使用
updateOrCreate
:
public static function insertReturned($itemId, $currentPackId)
{
ItemHistory::updateOrCreate([
'item_id' => $itemId,
'pack_id' => $currentPackId,
], [
'status' => self::RETURNED,
'returned_by' => Auth::id(),
]);
}
The first array is what you are looking for.第一个数组是您正在寻找的。 If a record is found fill it with the second array and save.
如果找到记录,则用第二个数组填充并保存。 If no record is found merge the first and second array and create the new record.
如果没有找到记录,则合并第一个和第二个数组并创建新记录。
Laravel 6.x Docs - Eloquent - Other Creation Methods updateOrCreate
Laravel 6.x 文档 - Eloquent - 其他创建方法
updateOrCreate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.