雄辩有许多通过多对多(belongsToMany)

时间:2017-08-22 04:09:28

标签: php mysql eloquent relationships

我有这个给定的表结构:

enter image description here

如何访问' curso.name'来自我的访问者'使用雄辩的课程? 我分配了多对多关系,但只能访问&{39; turma.curso_id',但我希望获得类似$visita->curso['nome']的内容。

我想知道如何避免需要Curso::all()

在下面添加了一些代码段:

// Class VISITA    
class Visita extends Model
{

      protected $fillable = [
        'id',
        'nome',
      ];

    public function turmas()
    {
        return $this->belongsToMany('App\Models\Turma', 'turma_disciplina_visita')->withPivot('disciplina_id');
    }

}

// Class TURMA
class Turma extends Model
{

    protected $fillable = [
        'id',
        'nome',
        'curso_id',
    ];

    public function curso()
  {
      return $this->belongsTo('App\Models\Curso');
  }

}

// Class CURSO
class Curso extends Model
{

    protected $fillable = [
        'id',
        'nome',
    ];

    public function turmas()
  {
      return $this->hasMany('App\Models\Turma');
  }

}

// Class VISITACONTROLLER
class VisitaController extends BaseController
{

  public function list($request, $response)
  {
    $visitas = Visita::all(); // brings me the visita and the turma with its attributes
    $cursos = Curso::all(); // wanted to get cursos without needing this extra query which brings me all the cursos..

    return $this->view->render($response, 'Visitas/list.php', [
        'visitas' => $visitas,
        'cursos'  => $cursos,
    ]);

  }
}

// View LIST.PHP

// This way I get the turma.nome
foreach ($visita->turmas as $turma){
  echo $turma['nome'] . '<br>';

// This way I get the curso.nome
foreach ($visita->turmas as $turma){
  echo $cursos[$turma['curso_id']] . '<br>';

1 个答案:

答案 0 :(得分:1)

您是否尝试过这样加载您的收藏:

Visita::with('turmas.curso')->all();

在你的前沿,你应该能够像这样加载你的数据:

foreach (($visita->turmas as $turma){
    $turma->curso->nome;
}

希望这有帮助