PlayHardGoPro
PlayHardGoPro

Reputation: 2923

Access both table data through relation

I have two tables with a Many-to-Many relation. So I created a third table:

professor < -- > turma | Pivot: professor_turma

Here is my model's code:

class Professor extends Model
{
    public function turmas()
    {
        return $this->belongsToMany('App\Turma', 'professor_turma',                'cod_professor', 'cod_turma');
    }
}

class Turma extends Model
{
    protected $table = 'turma';

    public function professores(){
        return $this->belongsToMany('App\Professor');
    }
}  

my Professor's Controller:(The one my route redirects to)

class ProfessorController extends Controller
{
    public function getProfessorList()
    {
        return View::make('professor', [
            'professor' => Professor::orderBy('nome','asc')->get()
        ]);
    }
}

In my view, I'm trying to access the data of both tables (Professor, Turma).

<ul class="prof-list col-md-4">
   @foreach($professor as $prof)        
      <li>
         <h3 data-id="{{ $prof->cod_professor }}" class="prof-name">{{ $prof->cod_professor }} - {{ $prof->nome }} 
            <input type="checkbox" name="" value="" class="check_prof" />
         </h3>

      <ul class="list-disc">
         @foreach($prof->turmas as $disc)
            <li data-dia="{{ $disc->dia_semana }}" data-time="{{ $disc->hr_inicio}}" data-id="{{ $disc->cod_disciplina }}">{{ $disc->nome_disciplina }}                 </li>
        @endforeach
     </ul>
  </li>
@endforeach

I'd like to know how could I access Turma's data without the second @foreach without using $disc. Is it possible? How ?

@foreach($prof as $disc)

Why I can't do something like:

@for($i = 0; $i < 1; $i++)
   {{ $professor->turmas[$i]->dia_semana }}
@endfor

Upvotes: 0

Views: 36

Answers (1)

Jhuliano Moreno
Jhuliano Moreno

Reputation: 989

The problem is that you need to eager load the "turmas" instead of lazy loading. This will also make your code more effecient since it won't query the DB for each "professor" row.
See: http://laravel.com/docs/5.1/eloquent-relationships#eager-loading

This should fix the problem:

Professor::with('turmas')->orderBy('nome','asc')->get()

Upvotes: 1

Related Questions