Yii2 model::find() with default where conditions

后端 未结 1 1289
小鲜肉
小鲜肉 2021-01-04 12:01

Using Yii2 in the View...

Products::find()->asArray()->all()

returns all products as array. I\'m looking for a way to make it return

相关标签:
1条回答
  • 2021-01-04 12:49

    1) You can simply override find() method in your model:

    /**
     * @return \yii\db\ActiveQuery
     */
    public static function find()
    {
        return parent::find()->where(['<>', 'id', 1]);
    }
    

    Usage:

    $products = Products::find()->all();
    

    2) Use scope.

    Create custom query class:

    namespace app\models;
    
    use yii\db\ActiveQuery;
    
    class ProductQuery extends ActiveQuery
    {
        public function withoutFirst()
        {
            $this->andWhere(['<>', 'id', 1]);
    
            return $this;
        }
    }
    

    Override find() method in your model:

    namespace app\models;
    
    use yii\db\ActiveRecord;
    
    class Product extends ActiveRecord
    {
        /**
         * @inheritdoc
         * @return ProductQuery
         */
        public static function find()
        {
            return new ProductQuery(get_called_class());
        }
    }
    

    Then you can use it like this:

    $products = Products::find()->withoutFirst()->all();
    

    I think using second method is more flexible, because it makes code more clear.

    Additional notes:

    • Hardcoded id is not good practice. Better replace it with equivalent condition.

    • For this examples I used different way of specifying condition. See different ways of specifying condition in where statement in official documentation.

    0 讨论(0)
提交回复
热议问题