M
M
mrSeller2018-04-06 23:20:05
Laravel
mrSeller, 2018-04-06 23:20:05

How to get the sequence number of a row in a selection with Eloquent ORM?

For example, I have a database of cities with a population.
I need Chelyabinsk and its place in terms of population among cities.
I get cities, sort them by population, but how to get its ordinal number in the selection?

$chelyabinsk_id = 100;
$city = City::where('people', '>', 100000)->orderBy('people')->?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yan-s, 2018-04-07
@mrSeller

Get the city number by its id:

$chelyabinsk_id = 100;
$сities = City::where('people', '>', 100000)->orderBy('people')->get();
$position = $сities->where('id', $chelyabinsk_id)->keys()->first());

But perhaps it would be better to calculate the position once and put it in the database than to do it every time.

H
hakkol, 2018-04-07
@hakkol

Make an array from the collection (toArray()), and then use array_search or array_filter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question