简体   繁体   English

根据交叉引用表为用户选择所有角色。 PDO MySQL子查询或JOIN

[英]Select all the roles for a user based on a cross reference table. PDO MySQL sub-query or JOIN

I tried the following code and it returned an empty array when I really expected it to return several rows. 我尝试了以下代码,当我真的希望它返回几行时,它返回了一个空数组。 My table layout is below the code. 我的表格布局在代码下方。 (Notice the commented version of $connection->prepare() I tried it both ways.) (注意,我尝试过两种方式的$connection->prepare()的注释版本。)

In case it is not obvious, what I am trying to do is find all the role-names assigned to a certain user if I know their user_id. 如果不太明显,我想做的就是在知道用户名的情况下,找到分配给该用户的所有角色名。 (the id column from the sl_user table). (sl_user表中的id列)。

function getrolesnamesbyuserid($user_id){ //returns role names
  $connection = new PDO('mysql:host=127.0.0.1;dbname='.DBNAME, DBUSER, DBPASS);
  if(!$connection){echo '<!-- DB CONNECTION ERROR -->';}else{/* echo '<!-- DB CONNECTION CONFIRMED -->'; */}
  $prep_get_roles=$connection->prepare('SELECT sl_role.name AS role_name FROM sl_role WHERE sl_role.id IN (SELECT sl_user_roles.role_id from sl_user_roles WHERE sl_user_roles.user_id = :user_id)');
  // $prep_get_roles=$connection->prepare('SELECT r.name AS role_name FROM sl_role r WHERE r.id IN (SELECT ur.role_id from sl_user_roles ur WHERE ur.user_id = :user_id)');
  $prep_get_roles->bindParam(':user_id',$user_id);
  $prep_get_roles->execute();
  return $prep_get_roles->fetchAll(PDO::FETCH_ASSOC);
}

sl_role sl_role

+-------+-------------+
| Field | Type        |
+-------+-------------+
| id    | int(11)     |
| name  | varchar(50) |
+-------+-------------+

sl_user_roles sl_user_roles

+---------+---------+
| Field   | Type    |
+---------+---------+
| user_id | int(11) |
| role_id | int(11) |
+---------+---------+

Just as a quick test, I was calling it like this: 为了快速测试,我这样称呼它:

var_export(getrolesnamesbyuserid($_SESSION['user_id']));

Am I heading in the right direction here? 我在朝正确的方向前进吗? If so, how do I fix it. 如果是这样,我该如何解决。 If not, how do I re-write this? 如果没有,我该如何重写? Maybe as a join, but I don't really don't have much experience with them. 也许是参加,但是我对他们并没有太多经验。

I've tried recreating your database structure and executing your code and can't recreate the problem, which means the error is in your data. 我尝试重新创建数据库结构并执行代码,但是无法重新创建问题,这意味着错误出在您的数据中。 Have you checked that your data in sl_user_roles is linking correctly, and that $_SESSION['user_id'] is actually set to something? 您是否检查过sl_user_roles中的数据正确链接,并且$_SESSION['user_id']实际上设置为某些值? Try inserting the following dummy rows and then replace $_SESSION['user_id'] in your var_export() line with 99999: 尝试插入以下虚拟行,然后将var_export()行中的$_SESSION['user_id']替换$_SESSION['user_id'] 99999:

INSERT INTO `sl_role` VALUES (99991, 'Foo');
INSERT INTO `sl_role` VALUES (99992, 'Bar');
INSERT INTO `sl_role` VALUES (99993, 'Bin');
INSERT INTO `sl_role` VALUES (99994, 'Baz');

INSERT INTO `sl_user_roles` VALUES (99999, 99991);
INSERT INTO `sl_user_roles` VALUES (99999, 99992);
INSERT INTO `sl_user_roles` VALUES (99999, 99994);

Your query should return the roles "Foo", "Bar", and "Baz". 您的查询应返回角色“ Foo”,“ Bar”和“ Baz”。 If it does so, then the error is in your data rather than your logic. 如果这样做,则错误出在您的数据中,而不是您的逻辑中。 You can delete the dummy rows with the following statements: 您可以使用以下语句删除虚拟行:

DELETE FROM `sl_role` WHERE `id` IN (99991, 99992, 99993, 99994);
DELETE FROM `sl_user_roles` WHERE `user_id` = 99999;

Obviously, check that you haven't got any users or roles with these ids before you do so. 显然,在进行操作之前,请检查是否没有具有这些ID的用户或角色。 :) :)

Also, I would recommend restructuring your query as follows: 另外,我建议按以下方式重组查询:

SELECT `r`.`name` AS `role_name`
FROM `sl_role` AS `r`
    LEFT JOIN `sl_user_roles` AS `ur`
        ON `ur`.`role_id` = `r`.`id`
WHERE `ur`.`user_id` = :user_id

This will be much more efficient than using a subquery. 这将比使用子查询更为有效。 Whilst lengthy, the MySQL JOIN Syntax documentation is well worth a read at some point. 虽然冗长,在MySQL的JOIN语法文档是非常值得在某些时候读取。 :) :)

I was unable to reproduce your error, create database and the php script for it, everything works fine. 我无法重现您的错误,无法为其创建数据库和PHP脚本,但一切正常。 Sure that everything is ok with your data and your query? 确定您的数据和查询一切正常吗?

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

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