Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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



42.3k
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');