Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 active record find column not equal

Tags:

I have this code to find a user from db which status is active and role is user

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

I need to find a user that role is not equal to "user". How can I do this?

P.S: I'm using YII2

like image 685
nsv Avatar asked Apr 09 '14 12:04

nsv


2 Answers

I want to offer another solution, it's more elegant for me. I usually use this approach since Yii 1 when i need check not equal operation.

$models = Book::find()->where('id != :id and type != :type', ['id'=>1, 'type'=>1])->all(); 
like image 57
Alex Avatar answered Sep 18 '22 08:09

Alex


You can pass custom where clause like this:

andWhere(['!=', 'field', 'value']) 

Your final function will look like:

public static function findByUsername($username) {     return static::find()         ->where([             'username' => $username,             'status' => static::STATUS_ACTIVE         ])         ->andWhere(['!=', 'role', 'user'])         ->all(); } 
like image 32
Stanimir Stoyanov Avatar answered Sep 22 '22 08:09

Stanimir Stoyanov