Select the last entry in the table.

How to select the last record (which has MAX(id) ) from the table?
The following statement works fine, but selects the first record:

 $statistics = SystemStatisticsHistory::findOne(1); 
+9
source share
2 answers

To get the model with the maximum id you can apply the reverse order and restriction to one.

 SystemStatisticsHistory::find()->orderBy(['id' => SORT_DESC])->one(); 

Another option is to use a subselect with max as follows:

 SystemStatisticsHistory::find() ->where(['id' => SystemStatisticsHistory::find()->max('id')]) ->one(); 

There are some nuances using the latter option, check this question .

You can check the documentation for max() here .

I personally prefer to use the first option.

To get the first record, simply change the direction of the order to SORT_ASC in the first request and from max() to min() in the second request.

PS Encoded id is bad practice.

+18
source

Optimized

 SystemStatisticsHistory::find()->select(['id'=>'MAX('id')'])->one()->id; 

OR if you want to increase by a number

 SystemStatisticsHistory::find()->select(['id'=>'( MAX('id')+ 1) '])->one()->id; 
0
source

Source: https://habr.com/ru/post/980887/


All Articles