Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 612
chang Avatar asked Feb 18 '15 07:02

chang


3 Answers

$maxdate=A::find()->max('created_date');
like image 160
mano Avatar answered Oct 22 '22 21:10

mano


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().

like image 30
topher Avatar answered Oct 22 '22 23:10

topher


Try this

$model = A::find()->orderBy("created_date DESC")->one();
like image 2
vitalik_74 Avatar answered Oct 22 '22 23:10

vitalik_74