Php 如何在laravel中连接三个表

Php 如何在laravel中连接三个表,php,laravel,eloquent,Php,Laravel,Eloquent,我想连接三个表: 章节表: 截面ID 文本 formid 问题表: 问题号 问题 formid 截面ID 选项表: 选项ID 选项 问题号 我想获取formid=x的所有部分(例如),以及与部分ID相关的问题和与问题ID相关的选项 $data=Section::with('questions','options') ->where('formId',$formId)

我想连接三个表: 章节表: 截面ID 文本 formid

问题表: 问题号 问题 formid 截面ID

选项表: 选项ID 选项 问题号

我想获取formid=x的所有部分(例如),以及与部分ID相关的问题和与问题ID相关的选项

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

根据您的需要: 笔记:
  • 不要从所有表中提取*,在大多数情况下,您可能会得到不明确的列错误
  • 您的编码风格没有遵循惯例,这是非常糟糕的做法。遵循惯例在很多方面都有帮助

  • 我在我的分区模型中创建了两个关系。一个是通过问题模型将截面模型连接到问题模型,另一个是通过问题模型将截面模型连接到选项模型

    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');
    }
    
    }

    我的控制器:

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

    它工作正常:)

    谢谢。我找到了解决方案并回答了我的问题。你的问题是关于
    join
    的,而你的答案与此相差甚远。不管怎么说,我建议你跟着laravel docs
                $data=Section::with('questions','options')
                                ->where('formId',$formId)
                                ->orderBy('sectionid')
                                ->get()
                                ->toJson();