Last active
March 5, 2021 19:08
-
-
Save chasecmiller/027896f5518d44141687cca4da4c10b7 to your computer and use it in GitHub Desktop.
Getting the row number for the current db entry in Laravel.
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
This is a very inefficient way to do it once the db is huge. But it works. For the example, the user id is 5. | |
$userId = 5; | |
\DB::statement('SET @row=0'); | |
$user = \App\Models\User::whereRaw('1=1') | |
->select([ | |
\DB::raw('@row:=@row+1 as row'), | |
\DB::raw('count(*) as c'), | |
'users.*' | |
]) | |
->groupBy('id') | |
->orderBy('c','desc') | |
->get() | |
->filter(function($entity) use ($userId) { | |
return $entity->getKey() == $userId; | |
}) | |
->first(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment