chang chang - 6 months ago 317
SQL Question

Yii2 select by max date?

Suppose I have table A with its active record in yii2, What is the best way to can load the record with max created date to the model.

This is the query :

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


Now I am getting the max date first then use it in another access to database ie:

$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 one access to database , but I don't know how.

please any help.

Answer

Your query is the equivalent of:

SELECT * FROM A ORDER BY created_date DESC LIMIT 1;

You can order your records by created_date in descending order and get the first record i.e:

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