This commit is contained in:
43
api/database/utils/SeederUtil.php
Normal file
43
api/database/utils/SeederUtil.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
class SeederUtil
|
||||
{
|
||||
public static function saveList($model, $items, $identifierKeys = [], $deleteIfNotPresent = false)
|
||||
{
|
||||
if (is_string($identifierKeys)) {
|
||||
|
||||
$identifierKeys = [$identifierKeys];
|
||||
}
|
||||
|
||||
$ids = [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
|
||||
$identifiers = [];
|
||||
|
||||
foreach ($identifierKeys as $key) {
|
||||
|
||||
$identifiers[$key] = $item[$key];
|
||||
}
|
||||
|
||||
if (empty($identifiers)) {
|
||||
|
||||
$ids[] = $model::create($item)->id;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$ids[] = $model::updateOrCreate($identifiers, $item)->id;
|
||||
}
|
||||
|
||||
if ($deleteIfNotPresent && !empty($ids)) {
|
||||
|
||||
$idsToDelete = $model::whereNotIn('id', $ids)->pluck('id');
|
||||
|
||||
if (!empty($idsToDelete)) {
|
||||
|
||||
$model::destroy($idsToDelete);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user