Laravel query builder - how to select a model whereHas one of multiple relationships

I have a Shop model that can has three relationships: Specials, Discounts and ThrowOuts. I want to select all Shops that have data in any one of those three relationships, but mask the ones that don't have any at all.

I also want to limit the search results based on properties of the Shop itself:

Shop::where('state', $state)
    ->whereHas('Discounts ')

This query requires that all the relationships have data - none can be blank

Shop::where('state', $state)
    ->orWhereHas('Discounts ')

Using orWhereHas returns all of the shops that have any data in those relationships regardless of the first "where" so I get shops from all over the country as well.

1 answer

  • answered 2021-03-03 01:41 Abraham Brookes

    ...aaand I've just answered my own question - group the results of the first where, and run the relationship queries on that grouping instead:

    Shop::where('state', $state)
        ->where(function ($query) {
            return $query->orWhereHas('Specials')
                         ->orWhereHas('Discounts ')