skip to Main Content

I have multiple many-to-many relationships and i want to filter through them.
The models are:

  • State
  • District

I attached an screenshot:

(https://i.stack.imgur.com/TJPwp.png)

States are Alabama and Arizona, Districts are Autaga, Baldwin and Apache

When i check Alabama and Arizona the query works and i get the requested items.
Now i only want items from Arizona and Autaga – but the query just returns items from Autaga.

$query->when($states, function ($query) use ($districts, $states) {
    $query->whereHas('states', function($query) use($states) {
        $query->whereIn('name', $states);
    });
});
$query->when($districts, function ($query) use ($districts, $states) {
    $query->where(function ($subQuery) use ($states, $districts) {
        $subQuery->whereHas('states', function($query) use($states) {
            $query->whereIn('name', $states);
        });
        $subQuery->whereHas('districts', function($query) use($districts) {
            $query->whereIn('name', $districts);
        });
    });
});

2

Answers


  1. Because you use and logic, the result must satisfy both conditions. So use orWhere, try:

    $query->when($districts || $states, function ($query) use ($districts, $states) {
        $query->whereHas('states', function($query) use($states) {
            $query->whereIn('name', (array) $states);
        });
    
        $query->orWhere( function($query) use($districts){
            $query->whereHas('districts', function($query) use($districts) {
                $query->whereIn('name', (array) $districts);
            });
        });
    });
    
    Login or Signup to reply.
  2. Here is solution of your query :

    if (!empty($districts)) {
        $query->whereHas('states', function($query) use($states) {
            $query->whereIn('name', $states);
        })
        ->whereHas('districts', function($query) use($districts) {
            $query->whereIn('name', $districts);
        });
    } else {
        $query->whereHas('states', function($query) use($states) {
            $query->whereIn('name', $states);
        });
    }

    Hope this will help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search