3
我有这个给定的表结构:雄辩有许多通过与多对多(belongsToMany)
我如何用雄辩从我的“产前检查”级访问“curso.name”? 我分配了多对多的关系,但只能访问'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>';
发布你的代码..让我们试试你.. –
你去... –