44 lines
901 B
PHP
44 lines
901 B
PHP
<?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);
|
|
}
|
|
}
|
|
}
|
|
}
|