简体   繁体   English

查询以从多对多关系中获取对象

[英]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. 我在Permissions表中存储了Permission对象。

I have an MTM_UsersPermissions table that maps multiple User objects to multiple Permission objects. 我有一个MTM_UsersPermissions表,该表将多个User对象映射到多个Permission对象。 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 . 如果User.id = 1Permission.id = 10 ,并且此用户具有此权限,则MTM_UsersPermissions中有一条ID_A = 1ID_B = 10

I want to get all the Permissions associated with a given User, knowing the User ID. 我想获取与给定用户关联的所有权限,并且知道用户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; 我有一个有点功能查询: 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) (其中user_id是用户的ID)

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. 我对JOIN语句没有太多经验。 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 在PHP MySQL查询中获取外键对象的干净方法

Using MySQL 5.5. 使用MySQL 5.5。

What am I missing? 我想念什么?

ilmiont 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: 您不必加入Users表,您的OTM_UsersPermissions表已经包含用于过滤结果的用户ID:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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