当我只有年份可用时,如何根据日期时间字段查询数据库中的行?

How to query database for rows based on datetime field when I only have the year available to me?

我需要 select 基于年份的 table 中的所有行,但是我唯一可以查询的字段是 DATETIME 可以读取的字段,例如2020-05-08 14:30:34.

我如何 return 仅基于年份的条目?

$records = MedicalRecord::find()
    ->where(['dateCreated' => '2020'])
    ->all();

你可以使用YEAR()函数,试试这个:

$records = MedicalRecord::find()
    ->where(['YEAR(dateCreated)' => 2020])
    ->all();

您可以使用 andWhere() 并与年初和年末日期进行比较。

可能值得记住的是,这相当于将日期作为字符串进行比较,但由于顺序是 YY-mm-dd,所以它有效。

$records = MedicalRecord::find()
    ->where(['>=', 'dateCreated', '2020-01-01 00:00:00'])
    ->andWhere(['<', 'dateCreated', '2021-01-01 00:00:00'])
    ->all();

这样yii生成针对数据库运行的代码

如果您可以保证您的应用程序只会 运行 针对支持 YEAR() 功能的数据库引擎,那么 Serghei 的答案可能是最好的。但是如果你想迁移到 PostgreSql,Oracle... 它会停止工作。