首页 > 解决方案 > Yii2:SQL查询中的函数

问题描述

我需要使用 Yii2 框架从名为 people 的表中选择 21 岁或以下的人。

人=(身份证,生日)

public static function findByBirthday($idper) {
    $query = Persons::find()
        ->select([
            Persons::tableName().".[[id]]", 
            Persons::tableName().".[[birthday]]"
        ])
        ->where([
            '<=',
            'select age(birthday, NOW())',
            21
        ])

    return $query->asArray()->all();
}

标签: postgresqlyii2

解决方案


如果生日是有效的 DATE 类型

public static function findByBirthday($idper) {
    $query = Persons::find()
        ->select([
            Persons::tableName().".[[id]]", 
            Persons::tableName().".[[birthday]]"
        ])
        ->where([
            '<=',
            'EXTRACE(year from age(birthday))',
            21
        ])

    return $query->asArray()->all();
}

或者

  ->where(   'EXTRACE(year from age(birthday))   <= 21')

推荐阅读