chang
chang

Reputation: 133

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.

Upvotes: 9

Views: 23067

Answers (3)

topher
topher

Reputation: 14860

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')->limit(1)->one();

Why limit(1)? As pointed out by nicolascolman, according to the official Yii documentation:

Neither yii\db\ActiveRecord::findOne() nor yii\db\ActiveQuery::one() will add LIMIT 1 to the generated SQL statement. If your query may return many rows of data, you should call limit(1) explicitly to improve the performance, e.g., Customer::find()->limit(1)->one().

Upvotes: 16

mano
mano

Reputation: 41

$maxdate=A::find()->max('created_date');

Upvotes: 4

vitalik_74
vitalik_74

Reputation: 4591

Try this

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

Upvotes: 2

Related Questions