Skip to content
Advertisement

Multi-Tenant App – Getting Username for Users from Pivot Table

I’m developing a multi-tenant application with single database approach. Each query is typically scoped by subdomain_id.

My database is structured as follows –

users : This table is shared by multiple tenants

JavaScript

subdomains:

JavaScript

subdomains_users: This is my pivot table

JavaScript

The relationships are defined as follows-

User:

JavaScript

Subdomain:

JavaScript

Throughout my application, I’m required to access the username attribute. However, as you can see, this isn’t straightforward; because a user can belong to multiple subdomains.

How do I go about retrieving the username of any user for the current subdomain?

Advertisement

Answer

You can do it like so:

in User model (assuming you have the current subdomain id in the session, or just replace it with what is appropriate for you):

JavaScript

and you’ll be able to call $user->username to get the username for the current subdomain

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement