feat: guess table key name instead of hard-coding "id"

This commit is contained in:
Phan An 2023-08-20 13:03:29 +02:00
parent 48f6bcc105
commit 4182411881
No known key found for this signature in database
GPG key ID: A81E4477F0BB6FDC
2 changed files with 9 additions and 5 deletions

View file

@ -17,9 +17,11 @@ trait SupportsDeleteWhereValueNotIn
/**
* Deletes all records whose certain value is not in an array.
*/
public static function deleteWhereValueNotIn(array $values, string $field = 'id'): void
public static function deleteWhereValueNotIn(array $values, ?string $field = null): void
{
$maxChunkSize = DB::getDriverName() === 'sqlite' ? 999 : 65535;
$field ??= (new static())->getKeyName();
$maxChunkSize = DB::getDriverName() === 'sqlite' ? 999 : 65_535;
if (count($values) <= $maxChunkSize) {
static::query()->whereNotIn($field, $values)->delete();
@ -36,11 +38,13 @@ trait SupportsDeleteWhereValueNotIn
return;
}
static::deleteByChunk($deletableIds, $field, $maxChunkSize);
static::deleteByChunk($deletableIds, $maxChunkSize, $field);
}
public static function deleteByChunk(array $values, string $field = 'id', int $chunkSize = 65535): void
public static function deleteByChunk(array $values, int $chunkSize = 65_535, ?string $field = null): void
{
$field ??= (new static())->getKeyName();
DB::transaction(static function () use ($values, $field, $chunkSize): void {
foreach (array_chunk($values, $chunkSize) as $chunk) {
static::query()->whereIn($field, $chunk)->delete();

View file

@ -323,7 +323,7 @@ class SongTest extends TestCase
self::assertNotSame(0, Song::query()->count());
$ids = Song::query()->select('id')->get()->pluck('id')->all();
Song::deleteByChunk($ids, 'id', 1);
Song::deleteByChunk($ids, 1);
self::assertSame(0, Song::query()->count());
}