0

I had 4 tables that look like this:

users
  id
classrooms
  id
classroom_user
  classroom_id
  user_id
assignments
  id
  classroom_id

A user is belongs to many classroom and a classroom has many assignment. How do i get all the assignment from all the classroom that i joined? My current code is look like this:

$request
  ->user()
  ->classrooms()
  ->with('assignments')
  ->paginate()

Yes, indeed, it load all the assignment from all the classroom that i joined, but the assignments is showed inside each classroom array, how do i get only array of assignment without the classroom? Thanks before.

  • take a look at hasManyThrough() https://laravel.com/docs/8.x/eloquent-relationships#has-many-through – Gert B. Feb 10 '21 at 13:07
  • yes i already take a look at it, if i followed it correctly, that will look like this `public function assignments() { return $this->hasManyThrough(Assignment::class, Classroom::class) }` but that doesn't work, since there's no foreign id on classroom table – Rommy Gustiawan Feb 10 '21 at 13:18
  • https://stackoverflow.com/questions/35306242/laravel-5-eloquent-hasmanythrough-belongstomanythrough-relationships does this help? – Gert B. Feb 10 '21 at 13:23
  • alright, i will take a look at it – Rommy Gustiawan Feb 10 '21 at 13:25
  • Are you wanting to get the assignments for a single user or multiple users at the same time? – Rwd Feb 10 '21 at 20:39

0 Answers0