Yii2 choose the maximum date?

Suppose I have table A with its active entry in yii2. What is the best way to load the record with the maximum date created into the model.

This is the request:

select * from A where created_date = ( select max(created_date) from A ) 

Now I get the maximum date first, and then use it in another access to the database, i.e.:

  $max = A::find()->select("created_date)")->max(); $model = A::find()->where("created_date = :date",[":date"=>$max])->one(); 

I am sure that this can be done with a single access to the database, but I do not know how to do it.

please help.

+5
source share
3 answers

Your request is equivalent to:

 SELECT * FROM A ORDER BY created_date DESC LIMIT 1; 

You can order your created_date entries in descending order and get the first ie entry:

 $model = A::find()->orderBy('created_date DESC')->one(); 
+13
source

try it

 $model = A::find()->orderBy("created_date DESC")->one(); 
+2
source
 $maxdate=A::find()->max('created_date'); 
+1
source

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


All Articles