代码之家  ›  专栏  ›  技术社区  ›  rajwa766

在什么条件下之前哪里不工作?

  •  0
  • rajwa766  · 技术社区  · 7 年前

    在这里,我覆盖了 find() 方法

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

    现在如果我使用这样的条件

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

    活动记录全局条件在条件I之前执行 使用in-Order model,然后使用Order model,其中覆盖 活动记录全局条件。

    如果我像这样使用活动记录条件

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

    在我的本地模型中,存在覆盖全局条件的。对…来说很难 使用和where重写每个where。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Muhammad Omer Aslam    7 年前

    您应该更改 where andWhere onCondition 在您的 BaseActiveRecord 我想这是一个别名 \yii\db\ActiveRecord 作为 parent::find() 返回的对象 ActiveQuery 如果你调查一下 find() 它在第行下面返回的方法

    \yii\db\ActiveRecord

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

    你可以在这里看到 customizing-query-class 添加额外条件

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

    现在如果你打电话

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

    它将生成以下查询

    SELECT * FROM `order` 
       WHERE (`status` = 3) 
       AND 
       ((`order`.`application_id` = 1) AND (`order`.`branch_id` = 2))
    
        2
  •  0
  •   Liauchuk Ivan    7 年前

    这就是Yii2 ActiveRecord 作品调用方法时 where() 它重置条件,即使不是空的,并且当您调用 andWhere() 它为现有条件添加了新条件。