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

使用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条)

报告相同问题?

悬赏问题

  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密