Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the condition from ActiveQuery->init()

Tags:

yii

yii2

On Yii2 i have this code in ProjectQuery

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

Obviously the deleted condition must always apply, but there could be cases where this isn't true (for example an option for the user to see his deleted projects). How can i override this condition? Do i have to use something different from init() ?

(note, i want to apply this condition to all kind of queries normally, that's why i used init() on ProjectQuery and not the ProjectSearch class)

like image 970
dgtal Avatar asked Nov 16 '25 14:11

dgtal


2 Answers

You can still use init() but to override the 0 you should bind a parameter.

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

So to create a query that only shows the deleted projects write something like this:

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

To show all projects, deleted and not deleted, you could add a function to the ProjectQuery object to modify it accordingly.

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

And then write your query like:

$query = Project::find()->includeDeleted();
like image 75
Jap Mul Avatar answered Nov 18 '25 20:11

Jap Mul


You can use onCondition() to override existing on conditions:

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

You can use where() in the same way if you want to override conditions added by where(), andWhere and orWhere().

like image 36
rob006 Avatar answered Nov 18 '25 19:11

rob006



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!