Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for whereNotIn? #315

Open
JoaoPedroDiasMonteiro opened this issue Sep 10, 2022 · 0 comments
Open

Support for whereNotIn? #315

JoaoPedroDiasMonteiro opened this issue Sep 10, 2022 · 0 comments

Comments

@JoaoPedroDiasMonteiro
Copy link

Description

Hello there! I think that the implementation of the whereNotIn method is very helpful,

User::search($search)->whereNotIn('id', [1, 2, 3]);

Let’s think that we need to search for a User, but filter them by $except & $only.

If we want to apply only the except filter, we can perform two queries to get the results

User::search($search)
    ->when($except, function (Builder $query) use ($except, $only) {
        $ids = User::whereNotIn('id', $except)->pluck('id')->toArray();
        
        $query->whereIn('id', $ids);
    })
    ->take(5)
    ->get();

But the things get harder when we want to combine the $except and the $only

User::search($search)
    ->when($except || $only, function (Builder $query) use ($except, $only) {
        $except = !$only && $except ?
            User::whereNotIn('id', $except)->pluck('id')->toArray() :
            $except ?? [];
        
        $values = is_array($only) ? array_diff($only, $except) : $except;
        
        $query->whereIn('id', $values);
    })
    ->take(5)
    ->get();

With the whereNotIn, we can combine both

User::search($search)
    ->when($except, fn (Builder $query) => $query->whereNotIn('id', $except))
    ->when($only, fn (Builder $query) => $query->whereIn('id', $only))
    ->take(5)
    ->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant