从ActiveQuery-> init()覆盖条件

时间:2018-05-04 09:21:56

标签: yii yii2

在Yii2上,我在ProjectQuery

中有这段代码
class ProjectQuery extends \yii\db\ActiveQuery
{
    public function init()
    {
        $this->andOnCondition(['deleted' => 0]);
        parent::init();
    }

显然,已删除的条件必须始终适用,但可能存在这种情况并非如此(例如,用户可以选择查看已删除的项目)。我怎样才能覆盖这种情况?我是否必须使用与init()不同的内容?

(注意,我想通常将此条件应用于所有类型的查询,这就是我在init()使用ProjectQuery而不是ProjectSearch类的原因

2 个答案:

答案 0 :(得分:1)

您仍然可以使用init()但是要覆盖0,您应该绑定参数。

public function init()
{
    $this->andOnCondition('deleted = :deleted', [':deleted' => 0]);
    parent::init();
}

因此,要创建仅显示已删除项目的查询,请执行以下操作:

$query = Project::find()->addParams([':deleted' => 1]);

要显示已删除但未删除的所有项目,您可以向ProjectQuery对象添加一个函数以进行相应的修改。

public function includeDeleted() {
    $this->orOnCondition(['deleted' => 1]);
    return $this;
}

然后编写您的查询:

$query = Project::find()->includeDeleted();

答案 1 :(得分:0)

您可以使用onCondition()覆盖现有的 $('#theme li').click(function () { if($(this).hasClass('open')){ //alert('aaa'); $(this).children('a').children('span').children('em').removeClass('glyphicon-menu-up'); $(this).children('a').children('span').children('em').addClass('glyphicon-menu-down'); } else { $(this).children('a').children('span').children('em').removeClass('glyphicon-menu-down'); $(this).children('a').children('span').children('em').addClass('glyphicon-menu-up'); } }); 条件:

on

如果您想覆盖public function init() { $this->andOnCondition('deleted = :deleted', [':deleted' => 0]); parent::init(); } public function includeDeleted() { $this->onCondition(null); // remove unused param from old ON condition unset($this->params[':deleted']); return $this; } where()andWhere添加的条件,则可以使用相同的where()