2017-04-13 52 views
1
id sm_id to_id 
1 3  2 
2 4  1 
3 3  3 
4 3  2 
5 3  3 
6 4  1 

如何計算 sm_id有多少次出現?使用laravel比較和計數兩個表格

我有兩個輸入,第一個sm_id和第二個to_id,我想根據輸入計數值的發生。

sm_id = 4 and to_id = 1預期的結果將是2

這裏是我試過

$us = \DB::table('mgs') 
       ->where('sm_id', '=', DB::raw('to_id')) 
     ->where('to_id', '=', DB::raw('sm_id')) 
       ->groupBy('sm_id') 
       ->count(); 

     print_r($us);die; 

回答

2

在表中,執行此操作:

\DB::table('msg')->where('sm_id', $smId)->where('to_id', $toId)->count(); 
+0

這樣一個愚蠢的問題,謝謝@alexey –

+0

很高興它有幫助。 –

0

試試這個代碼:如果你要計算給定sm_idto_id多少郵件

$us = \DB::table('mgs') 
      ->where('sm_id', '=', DB::raw('to_id')) 
      ->where('to_id', '=', DB::raw('sm_id')) 
      ->groupBy('sm_id', 'to_id') 
      ->count('sm_id', 'to_id'); 

print_r($us);die; 
-1

如果你有$sm_id$to_id作爲輸入,那麼你不需要爲你使用Laravel query builder所以很會照顧SQL注入的使用DB::raw

$us = \DB::table('mgs')->where(['sm_id'=>$sm_id,'to_id'=>$to_id])->count(); 
dd($us); 

dd()是laravel的方法,代表轉儲和模,所以你不需要單獨使用print_rdie

PS。我從腳本中使用了\DB,但我建議使用:Illuminate\Support\Facades\DB

+0

請留下評論關於反對票。 – Learner