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

Here is my query:

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

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")


This doesn't work: (it throws "something went wrong")

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

Try this

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();
$sql = 'SELECT rid FROM relations WHERE rootid IN (736, 781) 
         GROUP BY rid HAVING COUNT(rid) = 2)';

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

You can try this

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();

Try This

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

Try this

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