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

Criteria Model Self Table Alias

Hi,

I need to use alias of self model table. For ex: orders model

Orders model

self::query()
    ->where('Orders.status = :status:')
    ->bind(['status' => true])
    ->innerJoin("Users", "u.id = Orders.user_id", "u")
    ->execute();

I want to use o. instead of Orders. like following that:

self::query()
    ->where('o.status = :status:')
    ->bind(['status' => true])
    ->innerJoin("Users", "u.id = o.user_id", "u")
    ->execute();

How can i set alias of base query model?

Thanks



77.7k
Accepted
answer

You cant.

What you can do, is use the queryBuilder:

// service container context
$resultSet = $this->modelsManager->createBuilder()
    ->addFrom('Orders','o')
    ->where('o.status = :status:')
    ->innerJoin("Users", "u.id = o.user_id", "u")
    ->bind(['status' => true])
    ->execute();
edited Jul '17

Something related: if you have namespaces for your models, you might want to set aliases globally via modelsManager:

$di->setShared('modelsManager', function() {
    $mm = new \Phalcon\Mvc\Model\Manager();
    //Registers shorter aliases for namespaces in PHQL statements
    //public registerNamespaceAlias (mixed $alias, mixed $namespaceName)
    $mm->registerNamespaceAlias('m', __NAMESPACE__ . '\Models');
    return $mm;
});

i.e.

$mm->registerNamespaceAlias('m', 'MyNameSpace\MyModels');