yii2活动记录查找列不相等

Sar*_*oev 22 php yii2

我有这个代码从db中找到一个用户状态为活动且role为user的用户

public static function findByUsername($username)
{
 return static::find(['username' => $username, 'status' => static::STATUS_ACTIVE, 'role'=>'user']);
}
Run Code Online (Sandbox Code Playgroud)

我需要找到一个角色不等于"user"的用户.我怎样才能做到这一点?

PS:我正在使用YII2

Ale*_*lex 31

我想提供另一种解决方案,它对我来说更优雅.我通常使用这种方法,因为Yii 1,当我需要检查不相等的操作.

$models = Book::find()->where('id != :id and type != :type', ['id'=>1, 'type'=>1])->all();
Run Code Online (Sandbox Code Playgroud)


Sta*_*nov 27

您可以像这样传递自定义where子句:

andWhere(['!=', 'field', 'value'])
Run Code Online (Sandbox Code Playgroud)

你的最终功能如下:

public static function findByUsername($username)
{
    return static::find()
        ->where([
            'username' => $username,
            'status' => static::STATUS_ACTIVE
        ])
        ->andWhere(['!=', 'role', 'user'])
        ->all();
}
Run Code Online (Sandbox Code Playgroud)