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

Use Model\Query object from Model`s static methods

Hi,

public static function deleteAll(){
    $queryString = sprintf('DELETE FROM %s', self::getClass());

    $query = new Model\Query($queryString);
    $query->execute();
}

The code above does not works (because $query has no DI object). It doesnt throw errors eather, just silently drops request.

But if we use Model\Query\Builder to get Query object, $query will have proper DI object. So, this works:

public static function deleteAll(){
    $queryString = sprintf('DELETE FROM %s', self::getClass());

    $builder = new Model\Query\Builder();
    $mocQuery = $builder->from(self::getClass())->getQuery();

    $query = new Model\Query($queryString);
    $query->setDi($mocQuery->GetDi())
    $query->execute();
}

My questions is:

  1. Where Model\Query\Builder gets DI object?
  2. What is the correct way to make queries to DB from static methods like find or findFirst?


2.0k
Accepted
answer

I was a problem too wiuth this, and than i found a working code:

$query = new Phalcon\Mvc\Model\Query("DELETE FROM Articles WHERE presence_id=:presence_id:", \Phalcon\DI\FactoryDefault::getDefault());
$query->execute(array('presence_id' => $presenceId));


1.7k

Indeed, this will work just as I want.

I need to be more attentitive. I just missed this part from Builders source code

if (Z_TYPE_P(dependency_injector) != IS_OBJECT) {
    dependency_injector = NULL;
    PHALCON_CALL_CE_STATIC(&dependency_injector, phalcon_di_ce, "getdefault");