首页 > 解决方案 > 在 Laravel 中使用 () 获取数据嵌套关系

问题描述

我有一个包含关系的模型文件“学生”:

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

在我的实施模型中,我有这些关系:

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

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

我想检索一个包含所有数据的表。

我试过这个

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

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

有用。但我没有我想要的结果。我也想用and关系恢复implementations数据projectscore

我试过了,但它不起作用

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

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

非常感谢您的帮助!

标签: phplaraveleloquent

解决方案


你试过Event::with('students', 'students.implementations')了吗?您可以使用点符号预先加载关系的关系。


推荐阅读