0

I am overriding the find method and add the where condition globally thats working fine here is my code

class Order extends \common\components\ActiveRecord    

\common\components\ActiveRecord

namespace common\components;
use Yii;

use yii\db\ActiveRecord as BaseActiveRecord;

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]);
    }
}

The find is not working when i call the model from view like this

 echo  \common\models\Order::find()->where(['status'=>'0'])->count();
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
rajwa766
  • 604
  • 13
  • 31

3 Answers3

2

Since you're using where() inside the find function that you're using in ActiveRecord and then where() in this statement

echo  \common\models\Order::find()->where(['status'=>'0'])->count();

the second ends up overriding the first

What you need to do is to use andWhere() in all the cases where you need the original conditions that you put in ActiveRecord to work. Try thus:

echo  \common\models\Order::find()->andWhere(['status'=>'0'])->count();

This should work.

And again remember, use andWhere() in all places where the original condition needs to be applied

mrateb
  • 2,317
  • 5
  • 27
  • 56
1

Use andWhere() so your default condition not get overridden :

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]);
    }
}
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
1

Try to change with onCondition()

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