0
votes

I have a phalcon project (phalconphp.com)

I want to create a 3 table relationship User -> user_roles <- roles

User table: id, role_id

User_roles: id, user_id, role_id

Roles: id, code

I did:

Users.php

 $this->hasMany(
            'id',
            'UserRoles',
            'user_id'
        );

UserRoles.php

$this->belongsTo(
        'user_id',
        'Users',
        'id'
    );

    $this->belongsTo(
        'role_type_id',
        'Roles',
        'id'
    );

Roles.php

$this->hasMany(
            'id',
            'UserRoles',
            'role_type_id'        
        );

And I want simply in my controller:

$users = Users::find();

 foreach ($users as $user) {
            echo $user->id;
            echo $user->roles->code;
}

But get: Access to undefined property Users::roles

Can anyone help me solve this problem? Reference: https://docs.phalconphp.com/en/3.3/db-models-relationships

2

2 Answers

0
votes

Only problem was, Phalcon could not find my table names (although it was complete rewrite of robots example).

All I had to do is specify aliases for tables in relations.

0
votes

@chazecka an Important thing to note about phalcon relationships:

They make coding easier, however they create a crazy amount of queries. If you care about performance, keep an eye in the amount of queries that are being executed, sometimes the amount may not be the optimal. In this case you may need to use joins and https://olddocs.phalconphp.com/en/3.0.1/api/Phalcon_Mvc_Model_Query_Builder.html or https://docs.phalconphp.com/zh/3.3/db-phql