Yii2 高级查询

首先我们要自己写一个ActiveQuery 类并且继承 Yii2 的 ActiveQuery:

namespace api\models;

class ActiveQuery extends \yii\db\ActiveQuery
{
    const STATUS_ACTIVE = 0;

    public function active()
    {
        $this->andWhere(['status' => self::STATUS_ACTIVE]);
        return $this;
    }
}

然后要在 User Model 里面复写 find 方法:

public static function find()
{
     return new ActiveQuery(get_called_class());
}

这样我们就可以在控制器中就可以这样用了:

public static function find()
{
     return new ActiveQuery(get_called_class());
}

这样我们就可以在控制器中就可以这样用了:

User::find()->active()->all()

PS: 当然如果要细分的话可以自己写一个 UserQuery 继承 ActiveQuery 而不是写一个ActiveQuery继承ActiveQuery。

可以参考 huajuan 的代码。 最后感谢 @yiqing

来源地址:http://www.getyii.com/topic/36

posted on 2016-02-04 14:38  yhdsir  阅读(334)  评论(0编辑  收藏  举报

导航