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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With