We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Adding condition to all queries

Hi All,

i was wondering if there's any possibility to add a condition i.e. " ... WHERE is_deleted = 0 ... " to ALL select queries to database. I wanted to not worry about general conditions that must be called when all tables contains same field. The best would be if the condition will be added when using query builder, find methods and plain sql respectively. Thanks in advance :)

Zenek

edited May '14

You can create a base class for all your models that uses the query builder to execute a query (whatever type that is - select, update, delete etc.)

In that class and function you will have you can have something like this:

public function executeMyQuery()
{
    // This would need to be somewhere else but putting it here to give you some idea.
    $di      = $this->getDI();
    $manager = $di['modelsManager'];
    $builder = $manager->createBuilder();

    $this->includeDeleted($builder);

    // This comes from a query builder object
    $query = $builder->getQuery();

    $data = $query->execute();

    return $data;
}

protected function excludeDeleted($builder)
{
    $builder->andWhere('deleted = 0');
}


1.8k

Yeah, thanks :) I know this solution, I was thinking if there is some tricky solution for this. Anyway thanks for your effort ;)