Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

Query builder get count of one to many relation

i have tables like below,

tests

test_id, test_name,test_code,date,test_active,test_type

test_package_mapping

id, test_id, package_id

user_tests

id, test_id, user_id, marks_scored

Now i am displaying all the tests of selected package like below,

$package_ids = [1,2];
$alltests = DB::table('test_package_maping')->join('tests', 'test_package_maping.test_id', '=', 'tests.test_id')->whereIn('tests.test_type',['Online Prelims','Integrated Prelims'])
                        ->where('tests.test_active',1)
                        ->whereIn('test_package_maping.package_id',$package_ids )
                        ->groupBy('test_package_maping.test_id')
                        ->paginate(20);

in user_tests table i am storing user completed tests and it has one to many relationship with tests. example: one user can take a test more than 1 time. Now i want to fetch number of times current logged in user attended the tests. how to get count of user attended tests that should be joined to above query? Please help with this.

0 likes
3 replies

Please or to participate in this conversation.