esbenp / esbenp/bruno

Use with SoftDelete Models

Open
#30 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
PHP
Stars
163
Forks
70
PR merge metrics
No merged PRs in 30d

Description

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;
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.