yii2yii2-advanced-appyii-components

The custom ActiveRecord class not working when i call the find() method from view?


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();

Solution

  • 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