0

I want to join three tables: sections table: sectionid text formid

questions table: questionid question formid sectionid

options table: optionid option questionid

I want to fetch all sections where formid=x (for example) and questions related to sectionid and options related to questionid.

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

2 Answers 2

1

I've created two relationships in my Section model. One to joining Section model to Question model and other one to join Section Model to Option model through Question model.

class Section extends Model
{
  use HasFactory;
  protected $primaryKey='sectionid';
  public function options(){
      return $this->hasManyThrough(Option::class,Question::class,'sectionid','questionid');

}
public function questions(){
    return $this->hasMany(Question::class,'sectionid');
}

}

My Controller:

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

It works properly :)

Sign up to request clarification or add additional context in comments.

Comments

0

Laravel docs: https://laravel.com/docs/8.x/queries#joins

According to what you need:

$data = Section::where('formid', x)
            ->join('questions', 'sections.sectionid', '=', 'questions.sectionid')
            ->join('options', 'options.optionid', '=', 'questions.optionid')
            ->select('sections.*', 'questions.question as question', 'options.option as option')
            ->get();

Notes:

  1. Do not fetch * from all tables, for most cases you may get ambiguous column error
  2. Your coding style does not follow convention which is really bad practice. Following convention helps in many ways.

2 Comments

Thank you. I found the solution and answered to my question.@Psycho
your question was about join and your answer is nowhere close to that. Anyway, suggesting you to follow laravel docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.