How to render elements in a view based on ManyToMany relationship

So far I created 3 tables :

users, roles and users_roles and created phalcon project by using Phalcon tools as well as generated models, controllers and views (php) by scaffolding tables with Phalcon tools. I have established working many-to-many relationship between tables users and roles via intermediate table users_roles.

My intention is to show search results in 'user' search view in this manner - generated table shold be like this


        USER                        ROLES
        user1                        role1,role2,role3
        user2                        role2
        user3                        role1,role3 

Many-to-many relationship in Users model is :

public function initialize()
             ['alias' => 'UserRoles']);  <--- alias is a must. it wil be used later as  'userRoles' property in foreach... 



The code above should be in view , here is the code :

<table class="table table-bordered">
            <th>User roles</th>
        <?php foreach ($page->items as $user): ?>
                <td><?php echo $user->id ?></td>

                <td><?php echo $user->name ?></td>

                <td><?php  $roles = $user->userRoles;                         <------- code starts here
                foreach ($roles as $role)
                                 $tmp[] = $role->name;
                               echo join(',',$tmp);
                ?></td>                                                                   <------ until here 

                <td><?php echo $this->tag->linkTo(["users/edit/" . $user->id, "Edit"]); ?></td>
                <td><?php echo $this->tag->linkTo(["users/delete/" . $user->id, "Delete"]); ?></td>
        <?php endforeach; ?>

I hope this will help someone.. Regards.

Hey @zeljoba to get relations you have to use $model->getRelated('aliasName') in your case $user->getRelated('UserRoles'). More info

Good luck

edited 13d ago

Thank you for the inputs. Instead of I would have $roles = $user->getRelated("userRoles") instead of $roles = $user->userRoles What is the main difference or benefits ?

Hey @zeljoba to get relations you have to use $model->getRelated('aliasName') in your case $user->getRelated('UserRoles'). More info

Good luck

getRelated() get related records from db or cache, but the variable userRoles does not act as a magic getter

Not to be contrary, but getRelated() isn't necessary. You absolutely can use the alias name as a magic getter. I think the issue is the alias is set up as UserRoles (capital "U"), but you're referencing userRoles (lower "U"). Case matters, so capitalize properly and it should work.