MySQL Yii2 按最大日期选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28577991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:21:36  来源:igfitidea点击:

Yii2 select by max date?

mysqlactiverecordyii2

提问by chang

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.

假设我在 yii2 中有带有活动记录的表 A,可以将具有最大创建日期的记录加载到模型的最佳方法是什么。

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.

请任何帮助。

回答by topher

Your query is the equivalent of:

您的查询相当于:

SELECT * FROM A ORDER BY created_date DESC LIMIT 1;

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

您可以按created_date降序对您的记录进行排序并获得第一条记录,即:

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

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

为什么limit(1)?正如nicolascolman所指出的,根据Yii 官方文档

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

yii\db\ActiveRecord::findOne()不会也不yii\db\ActiveQuery::one()会将 LIMIT 1 添加到生成的 SQL 语句中。如果您的查询可能返回多行数据,您应该显式调用 limit(1) 以提高性能,例如 Customer::find()->limit(1)->one()。

回答by mano

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

回答by vitalik_74

Try this

尝试这个

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