简体   繁体   中英

Fetch data nested relations eloquent with() in Laravel

I have a model file "Student" that contains the relation :

 public function implementations()
 {
       return $this->hasMany(Implementation::class);
  }

In my Implementation model, I have theses relations :

public function score()
    {
        return $this->belongsTo(Score::class, 'id', 'implementation_id');
    }

public function project()
    {
        return $this->belongsTo(Project::class);
    }

I would like to retrieve a table with all its data.

I tried this

public function getStudents($id)
{
    $event = Event::where('id', $id)->first();
    $data = $event->students()->with('implementations')->get();

    return response()->json($data);
}

It works. But I do not have the result I would like. I would also like to recover the implementations data with the project and score relationships

I tried that but it does not work

public function getStudents($id)
{
    $event = Event::where('id', $id)->first();
    $data = $event->students()->with('implementations')->with('project', 'score')->get();

    return response()->json($data);
}

Thank you very much for your help!

Have you tried Event::with('students', 'students.implementations') yet? You can eager load relations of relations using the dot notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM