如何使用 Laravel Query Builder 计算两个相关的表?

How to count two related tables using Laravel Query Builder?

我的数据库中有两个 table

我的第一个table

还有我的第二个table

我想统计有多少个金牌会员,有多少个银牌会员...我想对每个类别做一个统计...列中的rif可以重复但是是关键加入两个 tables.. 我正在使用查询生成器,我想继续使用它。有人可以帮助我吗?

我尝试使用此代码但没有成功

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

试试这个:

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

如果您只想计算特定类别:

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

有关详细信息,请参阅 Laravel docs