rajwa766
rajwa766

Reputation: 644

And Where is not working before where condition?

Here I am overriding the find() method

class ActiveRecord extends BaseActiveRecord{
    public static function find() {
        return parent::find()
           ->where(['=',static::tableName().'.company_id',Yii::$app->user->identity->company_id])
           ->andWhere(['=',static::tableName().'.branch_id',Yii::$app->user->identity->branch_id]);
    }
}

Now if I use the condition like this

\common\models\Order::find()->where(['stastus'=>'3'])->count(); 

the Active Record global condition is executed before the condition I am using in Order model and after that the Order Model where overriding the active record global condition.

And if I use the Active Record condition like this

class ActiveRecord extends BaseActiveRecord{
    public static function find() {
        return parent::find()
           ->andWhere(['=',static::tableName().'.company_id',Yii::$app->user->identity->company_id])
           ->andWhere(['=',static::tableName().'.branch_id',Yii::$app->user->identity->branch_id]);
    }
}

There were in my local model overriding the global condition. Difficult for me to override each where with and where.

Upvotes: 0

Views: 361

Answers (2)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23788

You should change the where and andWhere to onCondition in your BaseActiveRecord which I suppose is an alias for \yii\db\ActiveRecord as the parent::find() return object of ActiveQuery if you look into the find() method it returns below line

\yii\db\ActiveRecord

 return Yii::createObject(ActiveQuery::className(), [get_called_class()]);

you can see here customizing-query-class to add an extra condition

class ActiveRecord extends BaseActiveRecord{
    return parent::find ()
            ->onCondition ( [ 'and' ,
                [ '=' , static::tableName () . '.application_id' , 1 ] ,
                [ '=' , static::tableName () . '.branch_id' , 2 ]
    ] );
}

Now if you call

\common\models\Order::find()->where(['status'=>'3'])->createCommand()->rawSql; 

it will generate the following query

SELECT * FROM `order` 
   WHERE (`status` = 3) 
   AND 
   ((`order`.`application_id` = 1) AND (`order`.`branch_id` = 2))

Upvotes: 1

Liauchuk Ivan
Liauchuk Ivan

Reputation: 2003

This is the way how the Yii2 ActiveRecord works. When you call method where() it reset conditions, even if was not empty and when you call andWhere() it add new condition to existing ones.

Upvotes: 0

Related Questions