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

Scoping to a value #31

Open
cyrillkalita opened this issue Mar 10, 2023 · 0 comments
Open

Scoping to a value #31

cyrillkalita opened this issue Mar 10, 2023 · 0 comments

Comments

@cyrillkalita
Copy link

@zachleigh - i know about withSetting.
It is a solid solution, but i do not think it scales very well
What would you say about this approach?

If the model's setting value is default, i do not expect to see a record in property bag.
If it is different from default, a record is in DB.

So:

/**
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $key
     * @param mixed $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWhereHasSetting(Builder $query, $key, $value = null): Builder
    {
        // if the $value matches the default,
        // we need to return all models that DO NOT have the key in their property bag
        // otherwise, we need to scope DB for records that have it
        $default = $query->getModel()->defaultSetting($key);
        // matches precisely
        if ($default === $value) {
            return $query->whereDoesntHave(
                'propertyBag',
                fn(Builder $builder) => $builder->where('key', $key)
            );
        }
        // first we "cast" the value as array - same way Eloquent will
        $value = json_encode(Arr::wrap($value));
        // however, for lookup to work, we need to wrap the lookup string in double quotes
        return $query->whereHas(
            'propertyBag',
            fn(Builder $builder) => $builder->where('key', $key)->whereRaw('`value` = ?', json_encode($value))
        );
    }
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