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

thomaskim's avatar

@jsartisan Weird. I just ran that query with a many-to-many relationship, and it worked out fine. I'm not sure why it's saying that the id column doesn't exist on yours when you have an id column on your labs, tests, and pivot tables.

I would try this then.

Lab::whereHas('tests', function ($q) uses ($tests) {
    $q->whereIn('tests.id', $tests);
})->get();
jsartisan's avatar
jsartisan
OP
Best Answer
Level 2

@thomaskim @veve286 @willvincent

I have done this . Although this code looks very dumb :/ .But it is working. :).


    public function getLabsHavingTests($tests)
    {
        $lab_ids = [];

        $lab_tests = LabTest::select('lab_id', DB::raw('count(*) as total'))
                        ->whereIn('test_id',$tests)
                        ->groupBy('lab_id')
                        ->get();

        foreach ($lab_tests as $lab_test) 
        {
            if(count($tests) == $lab_test->total)
            {
                $lab_ids[] = $lab_test->lab_id;
            }
        }


        $labs = Lab::whereIn('id',$lab_ids)->paginate(1);

        return $labs;
}

1 like
pmall's avatar

This query is tricky. With raw sql (pseudo code) :

SELECT l.* FROM labs AS l, lab_test AS t
WHERE l.id = t.lab_id AND t.id IN ($test_ids[0], $test_ids[1], ...)
GROUP BY l.id
HAVING COUNT(DISTINCT t.id) = count($test_ids)

The idea is you select all couple lab/test with a test id in the array. Then group the results by lab id and finally keep only the groups with exactly the expected number of distinct tests.

1 like
jsartisan's avatar

@pmall I did the same thing but that was in php. But your code is really cool !! I will try it for sure :) Thanks a lot guys !

Previous

Please or to participate in this conversation.