简体   繁体   中英

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. Eg, 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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM