Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get all parents that children all match attribute?

I have this parent table

id
1
2

and this children table

id parent_id status
1 1 3
2 1 2
2 2 3
2 2 3

I want to query the tables(using laravel elloquent) and get the parents that have all their children match status 3. For example here id = 2 in parent table matches this criteria

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m unable to test it, but this may work:

Parent::whereDoesntHave('children', function($query) {
    $query->where('status', '!=', 3);
})->whereHas('children')

The resulting SQL looks like this:

select 
  * 
from 
  `parents` 
where 
  not exists (
    select 
      * 
    from 
      `children` 
    where 
      `parents`.`id` = `children`.`parent_id` 
      and `status` != 3
  ) 
  and exists (
    select 
      * 
    from 
      `children` 
    where 
      `parents`.`id` = `children`.`parent_id`
  )

It selects only parents that have children and excludes the ones that has children with a status not equal to 3

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading