dqb78642 2013-09-16 16:31
浏览 35

有没有更聪明的方法来加载PHP和MySQL的多对多关系?

Say you have Users and Roles in a many-to-many relationship. Standard setup with following tables:

user            role           user_role
  user_id         role_id        user_id
  email           name           role_id

Preferably with as few queries as possible, what's a good way to load all users with all tags belonging to them? That is, I'd like to end up with users, each having an array of roles.


I'm currently thinking of using the following, which'll requires two queries.

  1. Get all users with group concatenated role ids.
  2. Get all role names in separate query
  3. Loop through users, explode role ids and connect them with names from role query as we go.

Any good/better/more efficient/cleaner/quicker alternatives? Any good way to do this in a single query?

  • 写回答

1条回答 默认 最新

  • doudengjin8251 2013-09-16 16:34
    关注

    To return all roles for all users

    <?php
        $array=array();
        $sql='SELECT user.email,role.name
        FROM user
        INNER JOIN user_role ON user_role.user_id=user.user_id
        INNER JOIN role ON user_role.role_id=role.role_id';
    
        $stmt = db::db()->query($sql);
        while($row=$stmt->fetch(PDO::FETCH_ASSOC))
        {
            if (!isset($array[$row['email']])){$array[$row['email']]=array();}
            array[$row['email']][]=$row['name'];
        }
    
    ?>
    

    To return all roles for a single user

    <?php
        $sql='SELECT user.email,role.name
        FROM user
        INNER JOIN user_role ON user_role.user_id=user.user_id
        INNER JOIN role ON user_role.role_id=role.role_id
        WHERE user.email=?';
    
        $stmt = db::db()->prepare($sql);
        $stmt->execute(array('anEmail@domain.com'));
        $roles=$stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>
    

    The above assumes that all users have at least one role. If not, use outer joins.

    评论

报告相同问题?

悬赏问题

  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection