title: ManytoMany Relation between 3 tables Laravel
body: <p>I have 3 tables with Models all belongToMany related with each other:</p>
  
  <ul>
  <li>Batchyear</li>
  <li>Grade </li>
  <li>Student </li>
  </ul>
  
  <p>A student may attend many <code>batchyears</code>, and will be have many <code>grades</code>, and each <code>grade</code> have many <code>students</code>. </p>
  
  <p>How to get the relationship via Eloquent so that a <code>student</code> is in a certain <code>grade</code> in a certain <code>batchyear</code>?</p>
  
  <pre><code>class Batch extends Model
  {
      public $guarded = [];
  
      public function students()
      {
          return $this-&gt;belongsToMany(Student::class);
      }
  
      public function grades()
      {
          return $this-&gt;belongsToMany(Grade::class);
      }
  }
  </code></pre>
  
  <p>and here is grade</p>
  
  <pre><code>class Grade extends Model
  {
      public $guarded = [];
  
      public function students()
      {
          return $this-&gt;belongsToMany(Student::class);
      }
  
      public function batches(){
          return $this-&gt;belongsToMany(Batch::class);
      }
  }
  </code></pre>
  
  <p>and students</p>
  
  <pre><code>class Student extends Model
  {
      public $guarded = [];
  
      public function batches()
      {
          return $this-&gt;belongsToMany(Batch::class)-&gt;withPivot(['batch_id']);
      }
  
      public function grades()
      {
          return $this-&gt;belongsToMany(Grade::class);
      }
  }
  </code></pre>
  
  <p>tables students . batches. grades. batch_student, batch_grade. and grade_student . dont solve the problem. if I select a grades student It shows all students even who are in previous batch in this grade. need a table like student_grade_batch. so 3 foreign keys.</p>