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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么