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

Use with SoftDelete Models #30

Open
chrisgillis opened this issue Sep 21, 2017 · 0 comments
Open

Use with SoftDelete Models #30

chrisgillis opened this issue Sep 21, 2017 · 0 comments

Comments

@chrisgillis
Copy link

If you try to filter like so:

filter_groups: [
  {
    filters: [
      {
        key:'deleted_at', value:null, operator: 'eq', not: true
      }
    ]
  }
]

on a model with the softdelete trait, the resulting query will look something like this:

select * from users where (deleted_at is not null) and deleted_at is null

I couldnt come up with a better solution in my app than by extending Genie\Repository like so:

abstract class EloquentRepository extends Repository
{
    /**
     * Override abstract Repository class to modify query builder such that if soft delete key is provided
     * in request filters, the soft delete scope is correctly modified
     * @return Builder
     */
    protected function createBaseBuilder(array $options = [])
    {

        $query = $this->createQueryBuilder();

        $this->applyResourceOptions($query, $options);

        $model = $this->getModel();

        $traits = class_uses(get_class($model), true);
        if (in_array(SoftDeletes::class, $traits)) {
            $deletedAtKey = $model->getDeletedAtColumn();
            $filter_groups = array_get($options, 'filter_groups', []);
            foreach ($filter_groups as $filter_group) {
                $filters = array_get($filter_group, 'filters', []);
                foreach ($filters as $filter) {
                    $key = array_get($filter, 'key');
                    $negating = array_get($filter, 'not');

                    if ($key == $deletedAtKey && $negating) {
                        $query->withTrashed();
                    }
                }
            }
        }

        if (empty($options['sort'])) {
            $this->defaultSort($query, $options);
        }

        return $query;
    }
}
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