简体   繁体   中英

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: 输出

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

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM