David.titan David.titan - 2 months ago 8
MySQL Question

Laravel table relationship for getting user list

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.

Answer

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();
Comments