Naresh Verma Naresh Verma - 8 months ago 33
SQL Question

compare and count from two tables using laravel

id sm_id to_id
1 3 2
2 4 1
3 3 3
4 3 2
5 3 3
6 4 1


How can I count how many occurences of a
to_id
an
sm_id
has?

I have two inputs, first
sm_id
and second
to_id
, I want to count occurence of values based on inputs.

Expected result for
sm_id = 4 and to_id = 1
would be
2


Here's the code I tried

$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;

Answer Source

If you want to count how many messages with given sm_id and to_id in the table, do this:

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