如何在laravel中编写子查询?

时间:2017-01-11 07:11:18

标签: php mysql laravel subquery laravel-query-builder

$get_duplicate=DB::select('select * from student_info a join ( select first_name, last_name, dob  from student_info group by first_name, last_name, dob having count(*) > 1 ) b on a.first_name = b.first_name and a.last_name = b.last_name and a.dob = b.dob join participant_info on participant_info.id = a.participant_id order by a.first_name ASC');

如何以Eloquent格式转换此查询。

这是我的模特。

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class StudentInfo extends Model
{
    //
    public $timestamps = true;
    protected $table = 'student_info';
    protected $guarded = array();
    public function student_participant_det(){
        return $this->hasOne('App\Model\ParticipantInfo', 'id','participant_id');

    }
}

请帮我转换为Eloquent格式

1 个答案:

答案 0 :(得分:0)

我已编辑过上一段代码。请试试这个。

$get_duplicate=DB::table('student_info as a')
->join(DB::raw('(SELECT first_name, last_name, dob  FROM student_info group by first_name, last_name, dob having count(*) > 1 b'), function($join) {
    $join->on('a.first_name', '=', 'b.first_name');
    $join->on('a.last_name', '=', 'b.last_name');
    $join->on('a.dob', '=', 'b.dob'); })
->join('participant_info','participant_info.id', '=', 'a.participant_id')
->orderBy('a.first_name', 'ASC') ->get();