2017-04-13 94 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