如何在Laravel中将查询编写为raw?

时间:2017-04-03 10:19:36

标签: php mysql laravel

这是我的问题:

SELECT rid
FROM relations
WHERE rootid IN (736, 781) 
GROUP BY rid HAVING COUNT(rid) = 2");

我正试图在Laravel中实现它。我怎样才能做到这一点? (“查询构建器和雄辩的方法对我来说都很好”)

这不起作用:(它会抛出“出错的地方”)

DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();

5 个答案:

答案 0 :(得分:5)

$sql = 'SELECT rid FROM relations WHERE rootid IN (736, 781) 
         GROUP BY rid HAVING COUNT(rid) = 2)';

$result = DB::SELECT($sql);

答案 1 :(得分:1)

你可以试试这个

DB::table('relations')
    ->select(DB::raw('count(*) as user_count, status'))
    ->whereRaw('rootid IN (736, 781)')
    ->groupBy('rid')
    ->having(DB::Raw('COUNT(rid) = 2'))
    ->get();

答案 2 :(得分:0)

试试这个

DB::table('relations')
->select(DB::raw('count(*) as user_count, status'))
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->having(DB::Raw('COUNT(rid) = 2'))
->get();

答案 3 :(得分:0)

试试这个

DB::table('relations')
->whereIn('rootid', [736, 781])
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();

答案 4 :(得分:0)

试试这个

DB::select(DB::raw('SELECT rid
FROM relations
WHERE rootid IN (736, 781) 
GROUP BY rid HAVING COUNT(rid) = 2")'));