Select last record in the table
20,954
To get the model with max id
you can apply reverse order and limit to one.
SystemStatisticsHistory::find()->orderBy(['id' => SORT_DESC])->one();
Another option is to use subselect with max
like so:
SystemStatisticsHistory::find()
->where(['id' => SystemStatisticsHistory::find()->max('id')])
->one();
There are some nuances using last option, check this question.
You can check the documentation for max()
here.
I personally prefer using first variation.
To get the first record, just change the order direction to SORT_ASC
in first query and max()
to min()
in second query.
P.S. Hardcoded id
is a bad practice.
Author by
MaksimK
Updated on July 09, 2022Comments
-
MaksimK almost 2 years
How to select last record (that is having
MAX(id)
) from the table?
Next statement works OK, but selects the first record:$statistics = SystemStatisticsHistory::findOne(1);
-
arogachev over 9 yearsGlad to help. Mark the answer as accepted in this case.