在laravel中使用查询构建器加入3表

时间:2018-04-27 04:33:49

标签: mysql laravel laravel-5.5 laravel-5.6

我有3个表格问题,注册,ssi_tracks我需要从注册表中获取与其他两个表相对应的详细信息

我需要根据注册情况获取详细信息 questions.question_schedul = 0,ssi_tracks.track_first_status

我已经写了查询但是它说这里找不到列是我的查询

 $register = DB::table('registrations')
            ->join('questions', 'registrations.registration_id', '=', 'questions.question_id')
             ->join('ssi_tracks','registrations.registration_id','=','ssi_tracks.registration_id')
             ->select('address', 'model', 'chassis', 'delivery_date','ssi_tracks.track_first_status')
            ->where([["questions.question_schedul", "=", $dropselected] and ['ssi_tracks.track_first_status',0]])
             ->get();

2 个答案:

答案 0 :(得分:1)

试试这个:

$register = DB::table('registrations as R')
             ->select('R.address', 'R.model', 'R.chassis', 'R.delivery_date','S.track_first_status')
             ->join('questions as Q', 'R.registration_id', '=', 'Q.question_id')
             ->join('ssi_tracks as S','R.registration_id','=','S.registration_id')
             ->where('Q.question_schedul', '=', $dropselected)
             ->where('S.track_first_status', '=', 0)
             ->get();

请确保您在问题表中使用了正确的列以匹配注册ID:

->join('questions as Q', 'R.registration_id', '=', 'Q.question_id')

答案 1 :(得分:0)

尝试此查询:

$register = DB::table('registrations')
             ->leftJoin('questions', 'registrations.registration_id', '=', 'questions.question_id')
             ->leftJoin('ssi_tracks','registrations.registration_id','=','ssi_tracks.registration_id')
             ->select('registrations.address', 'registrations.model', 'registrations.chassis', 'registrations.delivery_date','ssi_tracks.track_first_status')
             ->where(['questions.question_schedul'=>$dropselected,'ssi_tracks.track_first_status'=>0])
             ->get();