Ad

How To Count Two Related Tables Using Laravel Query Builder?

- 1 answer

I have two tables in my database

My first table

enter image description here

And my second table

enter image description here

I would like to count how many gold members exists and how many silver members exists... I want to do a single count for each category... The rif can be repeated in the column but is the key to join the two tables.. I'm working with Query Builder and I would like to continue work with that. Someone can help me?

I tried with this code but didn't work

$count = DB::table('table1')
    ->join('table2', 'table1.rif', '=', 'table2.rif')
    ->select(DB::raw('category')
    ->count();
Ad

Answer

Try this:

use Illuminate\Support\Facades\DB;

DB::table('table2')
    ->join('table1', 'table2.rif', '=', 'table1.rif')
    ->select(DB::raw('count(*) as count'), 'table1.category as category')
    ->groupBy('category')
    ->get();

If you want to count only a specific category:

DB::table('table2')
    ->join('table1', 'table2.rif', '=', 'table1.rif')
    ->where('table1.category', 'Silver')
    ->count()

See Laravel docs for more info.

Ad
source: stackoverflow.com
Ad