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

How to prevent having to type full relative path to Model in WHERE/JOIN clause when using self-written PHQL

This is not an issue of utomst importance but more in the category of an annoyance, and we don't like those right?

How do I prevent having to type the full path to the folder where my models are located in JOIN and WHERE clauses when using self-written PHQL?

I want go from

            SELECT COUNT(*) AS count
            FROM \Apps\Source\Models\User AS u
            JOIN \Apps\Source\Models\UserCompany AS uc ON uc.userId = u.id
            WHERE u.companyId = :cid:         

to:

            SELECT COUNT(*) AS count
            FROM User AS u
            JOIN UserCompany AS uc ON uc.userId = u.id
            WHERE u.companyId = :cid: 

Any ideas? All functions in the Phalcon\Mvc\Model\Manager seem to irrelevant when writing custom PHQL, which I like to do when writing longer queries.

Thx in advance.



77.7k
Accepted
answer
edited Jul '19

You can either register your model namespace alias:

$this->modelsManager
    ->registerNamespaceAlias('m','\Apps\Source\Models');
// usage:
$this->modelsManager->createBuilder()
    ->addFrom('m:User')
    ->innerJoin('m:UserCompany')

or you can use PHP's magic class constant:

$this->modelsManager->createBuilder()
    ->addFrom(\Apps\Source\Models\User::class)
    ->innerJoin(\Apps\Source\Models\UserCompany:class)

(i prefer the latter, since you can refactor and catch naming errors in the IDE)



2.7k
edited Jul '19

The second example is still long, which I wanted to avoid, but I acknowledge the advantages you mention.

Using the colon character to trigger the alias is not mentioned in the documentation for the registerNamespaceAlias function. I had tried the function, but was not aware of having to use the colon. It should be added to the docs: https://docs.phalcon.io/3.4/de-de/api/Phalcon_Mvc_Model_Manager

Anyway, thanks!