Working with many-to-many relations - filters and roles

Posted 1 year ago by rikw

Hi all,

I'm working on a project based on a legacy database structure. This turns out to be easier than I expected so I'm happy with that. Now I run into design/architectual issue/question with the m2m relationships. Let me explain....

I have users that can have multiple roles in multiple organizations. For this I have four tables:

  • users
  • organizations
  • users_organizations - user_id, organization_id, role_code
  • roles - role_id, role_code, role_name

With a hasManyThrough I relate the users to the organization through the users_organizations table. Because the entities are related through other fields than the primary key I need to configure those too. This works fine.

    public function users()
        return $this->hasManyThrough(
        )->select(['role_code'])->where('role_code', '=', 'ContactOrg');


My current hasManyThrough filters the users so I only get users with a role code of 'ContactOrg'. This is not flexible of course. What is the advised way to proceed?

At some points in my code I want to know if a user has a specific role in a specific organization. This is the reverse of the shown hasManyThrough. What is the trick to get this info? Maybe I can distill this from the answer to my previous question.

How would I incorporate the roles table so I can show role names in my application?

Thank you in advance for thinking with me.

Cheers! Rik

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.