dspld86684 2016-12-11 17:48
浏览 24

Laravel雄辩地说出了多对多关系决定了是否存在关系

I am working on a project with many-to-many relationship between two tables roles and users. I also have a pivot table role_user that holds information about the relation between the other two tables.

role_user two fields namely the ids of the two tables: role_id and user_id.

Now I have a user object gotten from the users table and another role object gotten from the roles table. I want to determine if a particular role belongs to a certain user.

I know this can be done by creating a model for the pivot table and then using the model, the role_user table can be queried and determined if the relation exists. But I find this method stressful and wonder if eloquent provides an easy method to determine this. Thanks for any help?

  • 写回答

1条回答 默认 最新

  • dongshi8038 2016-12-11 20:00
    关注

    You don't need to have a role_user model. You might already have role model and the user model related to the tables you have. Specify the many to many relationship in Role.php and User.php

    User.php - function roles

        public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
    

    Role.php - function users

        public function users()
    {
        return $this->belongsToMany('App\User');
    }
    

    You may have to define other parameters like pivot table etc if you don't follow the naming conventions in table columns and tables. Since you seem to have follow the rules I'm not going to explain it. But you always can refer to laravel documentation's eloquent many-to-may section

    now you can easily check whether a user belongs to a certain role. Consider the following examle

        //select a user 
        $user = App\User::find(1);
        //select a role
        $role = App\Role::find(1);
        //get $user's roles. This ill return an array of role objects that are belong to $user
        $userRoles = $user->roles;
        //check whether $role is in that array
        if(in_array($role, $userRoles)){
        //do something
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP