简体   繁体   English

如何连接 laravel 中的表

[英]How to join tables in laravel

I have three tables that want to join them together.我有三个表想将它们连接在一起。 first table is questions, second is sections and third is options.第一个表是问题,第二个是部分,第三个是选项。 I want to fetch all records of table questions where formid for example is 120 and all records of table sections where it's questionid is equal to questionid of fetched questions table questionid.我想获取表格问题的所有记录,例如,formid 是 120,并且它的 questionid 等于所获取问题表格 questionid 的 questionid 的表格部分的所有记录。 And all record of third table 'options' where options.questionid=questions.questionid.以及第三个表“选项”的所有记录,其中 options.questionid=questions.questionid。

    $questions=DB::table('sections')
            ->rightJoin('questions',function($join ){
                $join->on('questions.questionid','=','sections.questionid');
            })
            ->leftJoin('options',function($join ){
                $join->on('questions.questionid','=','options.questionid');
            })
            ->where('questions.formid',$formId)
            ->get();

This code return null for questionid where no matched in sections table.此代码返回 null 用于在节表中没有匹配的 questionid。 How to solve this issue?如何解决这个问题?

Try it.试试看。

$questions=DB::table('questions')
        ->join('sections',function($join ){
            $join->on('questions.questionid','=','sections.questionid');
        })
        ->join('options',function($join ){
            $join->on('questions.questionid','=','options.questionid');
        })
        ->where('questions.formid',$formId)
        ->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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