2017-08-22 90 views
3

我有這個給定的表結構:雄辯有許多通過與多對多(belongsToMany)

enter image description here

我如何用雄辯從我的「產前檢查」級訪問「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>'; 
+1

發佈你的代碼..讓我們試試你.. –

+0

你去... –

回答

0

你試圖加載您的收藏這樣的:

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

而在你frontent你應該能夠加載這樣的數據:

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

希望這會有所幫助