2018-04-26 11:46
浏览 198

使用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', '', '=', 'role_user.user_id')
            ->join('roles', '', '=', 'role_user.role_id')
            ->where('', '=', 12)

图片转代码服务由CSDN问答提供 功能建议

我有3个表 - users,roles和role_user。 每个用户都被分配到role_user表中的角色,角色列表可以在角色表中找到。 我想选择角色ID为12的所有用户。我目前正在使用查询构建器执行此操作,但我需要它以雄辩的格式。 我对Laravel雄辩并不是很好,我需要帮助才能将查询转换为雄辩。 这就是我目前正在做的事情:

  $ users = DB :: table  ('用户')
  - >加入('role_user','','=','role_user.user_id')
  - >加入('roles','','  =','role_user.role_id')
  - > where('','=',12)
  - > get(); 
 <  / DIV>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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','', '=', 'role_user.user_id') ->join('roles', '', '=', 'role_user.role_id') -> where('', '=', 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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题