Skip to content
Advertisement

How to make relationship between three table in laravel eloquent

I have three tables, Sections,Questions and options. Each Section has many questions and each question has many options. How can I fetch data from this tables related to each other?

Section model relationship with Question model

      class Section extends Model
      {
      use HasFactory;
      protected $primaryKey='sectionid';
       public function questions(){
       return $this->hasMany(Question::class,'sectionid')->orderBy('order');
     }
   }

Question model relationship with Option model:

class Question extends Model
{
  use HasFactory;
   protected $primaryKey='questionid';
   public $timestamps = true;
   public function options(){
     return $this->hasMany(Option::class,'questionid');
  }
}

my query:

            $data=Section::with('questions')
                            ->where('formid',$formId)
                            ->orderBy('sectionid')
                            ->get()
                            ->toJson();

It returns this: output

I want each questions member contains options array related to it.

Advertisement

Answer

You can use nested relation in with like below.So it will fetch question options also

 $data=Section::with(['questions','questions.options'])
                            ->where('formid',$formId)
                            ->orderBy('sectionid')
                            ->get()
                            ->toJson(); 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement