algolia / scout-extended

Scout Extended: The Full Power of Algolia in Laravel
https://www.algolia.com/doc/framework-integration/laravel/getting-started/introduction-to-scout-extended/
MIT License
393 stars 85 forks source link

Support for whereNotIn? #315

Open JoaoPedroDiasMonteiro opened 1 year ago

JoaoPedroDiasMonteiro commented 1 year ago

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();