将SELECT查询从mySql转换为Laravel查询生成器

时间:2018-11-23 23:52:01

标签: mysql laravel

mysql 查询的 Laravel查询生成器代码是什么;

SELECT * 
FROM Student
WHERE family_id IN (SELECT family_id 
                    FROM students 
                    GROUP BY family_id 
                    HAVING COUNT(1)>1)
ORDER BY family_id

2 个答案:

答案 0 :(得分:1)

$query = DB::select("SELECT * 
FROM Student
WHERE family_id IN (SELECT family_id 
                    FROM students 
                    GROUP BY family_id 
                    HAVING COUNT(1)>1)
ORDER BY family_id")

基于Laravel Documentation

答案 1 :(得分:0)

在whereIn子句中使用函数:

Student::whereIn('family_id', function($query) {
   $query->select('family_id')
     ->from(with(new Students)->getTable())
     ->groupBy('family_id')
     ->havingRaw('COUNT(1) > 1')
})->get();