0

I have 3 model: Course,group,student

I want to give games from Course with 2 relations.

for ex: I want students of Course 1 (id=1)

The Course has Many group(5,6,8) and each group have One(36,38) or Many(35,37) students

How to get all students of Course with relations and eloquent

Mohammad Hosseini
  • 1,649
  • 1
  • 16
  • 31
  • Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – Dang Nguyen Dec 15 '18 at 01:09

2 Answers2

2

You can use hasManyThrough

 public function games()
 {
    return $this->hasManyThrough(Tournament::class, Group::class);
 }

The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country.

https://laravel.com/docs/5.7/eloquent-relationships#has-many-through

Anar Bayramov
  • 11,158
  • 5
  • 44
  • 64
1

If you need only games:

$games = Game::with(['some_relation_name', 'some_relation_name_2'])
    ->whereHas('group', function($query) {
        $query->whereHas('tournament', function($query) {
            $query->where('id', 1)
        });
    })
    ->get();

If you need tournament with games, Anar's option is better.

IndianCoding
  • 2,602
  • 1
  • 6
  • 12