I have a model with the following code:
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.
I'm using laravel php
You can adjust your method to use updateOrCreate
pretty easily:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.