2017-04-03 112 views
1

这里是我的查询:如何在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(); 
+0

你可以用'DB ::原始()'方法 –

回答

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

我已经编辑我的代码。有一个小问题。你可以看看吗? – stack

+0

你编辑了什么?请突出显示? – Qazi

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

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

这正是我所期待的。给予好评 – stack

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

尝试这个

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

试试这个

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