ilmiont
ilmiont

Reputation: 2151

Querying to get objects from a many-to-many relationship

I have User objects stored in a Users table.

I have Permission objects stored in a Permissions table.

I have an MTM_UsersPermissions table that maps multiple User objects to multiple Permission objects. If User.id = 1 and Permission.id = 10, and this user has this permission, there is a record in MTM_UsersPermissions with ID_A = 1 and ID_B = 10.

I want to get all the Permissions associated with a given User, knowing the User ID.

I have a somewhat functional query: SELECT Permissions.id, Permissions.Name, Permissions.Title, Permissions.Description, Permissions.OwnerURI FROM Permissions JOIN OTM_UsersPermissions ON OTM_UsersPermissions.ID_B = Permissions.id JOIN Users ON OTM_UsersPermissions.ID_A = :user_id;

(where user_id is the ID of the user)

This does seem to be retrieving only the permissions associated with each user. However, each permission is duplicated by the number of users present in the Users table. E.g., if the user has one permission assigned, but there are five users total, the correct permissions will be retrieved, but there will be five of each.

I don't have much experience with JOIN statements. I have tried to use this answer to get a working solution, but something's still lacking. Clean way to get foreign key objects in PHP MySQL query

Using MySQL 5.5.

What am I missing?

ilmiont

Upvotes: 0

Views: 46

Answers (1)

Attila Gyukics
Attila Gyukics

Reputation: 108

You don't have to join Users table, your OTM_UsersPermissions table consists the user id already which will be used for filtering the result:

SELECT Permissions.id, Permissions.Name, Permissions.Title, Permissions.Description, Permissions.OwnerURI FROM Permissions JOIN OTM_UsersPermissions ON OTM_UsersPermissions.ID_B = Permissions.id
WHERE OTM_UsersPermissions.ID_A = :user_id;

Upvotes: 1

Related Questions