dongxianghuan3587 2016-09-20 11:51
浏览 41
已采纳

用于获取用户列表的Laravel表关系

I'm working on a laravel 5 application. I have 3 tables:

table A: 'users' 

id   |    name
————————————————
1    |    Dave
2    |    Robet
3    |    Jimmy
4    |    Daniel

and Table B classroom_users

user_id | classroom_id 
1       | 5            
4       | 5            
3       | 6  
4       | 5          

I need to return all users 'name' for classroom 5

Please let me know what is the best way to do that. Trough model or Database join

Any help appreciated.

  • 写回答

2条回答 默认 最新

  • dousu8456 2016-09-20 12:01
    关注

    Assuming you have models and its relationships will be defined as below:

    Classroom Model:

    public function users(){
        return $this->belongsToMany(User::class,'classroom_users','classroom_id','user_id');
    }
    

    User Model:

    public function classrooms(){
        return $this->belongsToMany(UserClassrooms::class,'classroom_users','user_id','classroom_id');
    }
    

    Now, in controller you can retrieve the users belonging to the classroom id 5 as below:

    $classroom_id = 5 ;//change this to the id you want
    $users = Classroom::find($classroom_id)->users()->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!