doukui7574 2018-04-26 11:46
浏览 208
已采纳

使用Laravel Eloquent选择多个表

I have 3 tables - users, roles, and role_user. Each user is assigned to a role in the role_user table and the list of roles is found on the roles table. I want to select all users with role id of 12. I am currently doing this with the query builder but I need it to be in eloquent format. I am not really good with Laravel eloquent, please I need help in convert the queries to eloquent. This is what I am currently doing:

 $users = DB::table('users')
            ->join('role_user', 'users.id', '=', 'role_user.user_id')
            ->join('roles', 'roles.id', '=', 'role_user.role_id')
            ->where('roles.id', '=', 12)
            ->get();
  • 写回答

4条回答 默认 最新

  • dtwbp26022 2018-04-26 12:46
    关注

    To run your same DB query in an eloquent format, you would have to do the following:

    1. You should have a User model created which should be created with your project if you enabled laravel authentication which you could read more on here. If not you have to create your Models.
    2. To use the Models in your controller or Class, you have to enable it in your php file:

      use App\User;

    3. Run your reference to the User model like so.

      $users = User::join('role_user','users.id', '=', 'role_user.user_id') ->join('roles', 'roles.id', '=', 'role_user.role_id') -> where('roles.id', '=', 12) ->get();

    $users will now be a collection and subject to all the great methods available with a collection.

    I suggest taking some time to run through a free video tutorial on laracast to really understand how Model's are used with Eloquent. Additionally would be good to review the out of the box Auth features available. I tend to make all my calls to roles using Auth. Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥18 深度学习tensorflow1,ssdv1,coco数据集训练一个模型
  • ¥100 关于注册表摄像头和麦克风的问题
  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办
  • ¥15 数据库一张以时间排好序的表中,找出多次相邻的那些行
  • ¥50 关于DynamoRIO处理多线程程序时候的问题
  • ¥15 kubeadm部署k8s出错
  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方