I have this given table structure:
How can I access the 'curso.name' from my 'visita' class using eloquent?
I assigned the many to many relationships but can only access the 'turma.curso_id
', but I wanna get something like $visita->curso['nome']
.
I wanna know how to avoid needing Curso::all()
.
Added some snippets below:
// 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>';