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

Model relation question

Hello i am pretty new to phalcon and have not a question about the models. I have the following tables:

User Table:

    +----+-----+
    | id | name  
    +----+-----+
    |  1 | User1   
    |  2 | User2  
    |  3 | User3
    +----+-----+

UserRole Table:

    +----+-----+
    | userid | roleid  
    +----+-----+
    |  1 | 1   
    |  1 | 2  
    |  2 | 1  
    |  3 | 2
    +----+-----+

Roles Table:

    +----+-----+
    | id | name  
    +----+-----+
    |  1 | Role1   
    |  2 | Role2  
    +----+-----+

Now i can collect all Roles of the User like this. Its working.

$res =$user->findFirst()->getUserRoles();
        foreach($res as $userRole){
            var_dump($userRole->getRole()->getName());
        }

But i am wondering if thats the correct way or if its also possible to get the Roles directly? like : Or is that only possible if i write my own method in the User Model class?

    $user->findFirst()->getRoles();

Thanks for your advice. Patrick

you can take a look on database adapter from incubator for a more direct way

https://github.com/phalcon/incubator/blob/2.0.x/Library/Phalcon/Acl/Adapter/Database.php

edited Oct '15

Use modelsManager or static query method for select from UserRole and join Role/User. To be honest its only one good method you should use if you dont gonna edit it, for example for display in indexAction, no reason at all using models and multiple select query when you can do the same in just one query.