Yii2 model::find() with default where conditions

萝らか妹 提交于 2019-12-18 19:23:28

问题


Using Yii2 in the View...

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

returns all products as array. I'm looking for a way to make it return all products WHERE id != 1 I want to have only one place do modify what "->all()" returns for every model. I know that Product::find()->where('id != 1')->... is possible, but I don't want to write and maintain it in more than one place.


回答1:


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.



来源:https://stackoverflow.com/questions/28545910/yii2-modelfind-with-default-where-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!