Last active
February 9, 2024 18:00
-
-
Save ronssij/ebd355ff16c49f011c5690bd14069b37 to your computer and use it in GitHub Desktop.
Laravel: Sequentially Incrementing Null Columns in a Database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Database\Seeders; | |
use Illuminate\Database\Seeder; | |
use Illuminate\Support\Facades\DB; | |
class SequentialIncrementNullColumns extends Seeder | |
{ | |
public function run(): void | |
{ | |
$maxPosition = '(SELECT IFNULL(MAX(`position`), 0) FROM `sections`)'; | |
DB::transaction(function () use ($maxPosition) { | |
DB::statement("SET @pos := $maxPosition"); | |
DB::update("UPDATE `sections` SET `position` = (@pos := @pos + 1) WHERE `order` IS NULL AND `position` IS NULL ORDER BY `id`"); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another way.
SQL Query
~ OR ~
Eloquent