简体   繁体   中英

Laravel Query whereHas and whereIn

In my code I'm applying multiple search filters. Below is the core part where I don't get the expected result.

The result should be users that have a specific post connected to it or no posts connected to it (as expected through whereHas ) AND has a specific status (example below available_now ).

But the below query results also gives the specific result type where the user has a specific post connected (expected) but the result includes users with a status other than available_now (unexpected).

I would like the query to apply both conditions. Am I missing something?

$users = User::query();

$users = $this->filter1($users);
$users = $this->filter2($users);

private static function filter1($users) {
    $post_id = 5;

    $users->whereHas('posts', function ($query) use ($post_id) {
        $query->where('id', $post_id);
    })->orDoesntHave('posts');

   return $users;
}

private static function filter2($users) {
    $availability = array('available_now');
    $users->whereIn('availability', $availability); // I'm using whereIn because in some cases the $availability array has multiple values

    return $users;
}

return $users->get();

I think the problem comes from the orDoesntHave . Make use of the parenthesis in your query to make sure your conditions work as expected:

$users = User::query();

$users = $this->filter1($users);
$users = $this->filter2($users);

private static function filter1($users) {
    $post_id = 5;

    $users->where(function ($query) use ($post_id) { //Will add parenthesis around this part of the query
        $query->whereHas('posts', function ($subquery) use ($post_id) {
            $subquery->where('id', $post_id);
        })->orDoesntHave('posts');
    });

   return $users;
}

private static function filter2($users) {
    $availability = array('available_now');
    $users->whereIn('availability', $availability);

    return $users;
}

return $users->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM