spatie/laravel-searchable

Issues when using ModelSearchAspect with closure

voydz opened this issue · 4 comments

voydz commented

Hi,

so today I was working on a more complicated search implementation. It required searching a related model. I browsed the issues in this repo and quickly came up with the following solution:

# Note: as I changed model and field names for demo purposes I do not claim that this code will work as-is,
# but it should give an understanding of what I am trying to achieve.

# query stored in var $term

$search = (new Search())
  ->registerModel(MyModel::class,
      function(ModelSearchAspect $modelSearchAspect) use ($term) {
          $modelSearchAspect
              ->addSearchableAttribute('name')
              ->orWhereHas('my_relation', function ($query) use ($term) {
                  $searchTerm = mb_strtolower($term, 'UTF8');
                  $query->whereRaw('LOWER(my_related_field) LIKE ?', ["%{$searchTerm}%"]);
              });
      })
  ->search($term);

Unfortunately this results in the SQL:

select * from `my_model` where exists (select * from `my_relation` where `my_model`.`my_relation_id` = `my_relation`.`id` and LOWER(my_related_field) LIKE ?) and (LOWER(name) LIKE ?)

# Notice the last `and` here. Despite using `orWhereHas` the query builder builds a SQL which forces both conditions to be true.

I had a look at the source and quickly found the issue with no possible workarounds. I don't know if this is an intended behavior. Not going into much details I figured out the IMHO best solution to make it work. In the end it boils down to how the Laravel query builder works with where and orWhere under the hood.

As soon as I prepared an PR I will link it in this issue.

best regards

I found your PR fix for this issue which I've just run into today. Is there a clean solution that can be done for this issue until this is merged in, that you can suggest?

voydz commented

Hi @tooshay ,

I currently use this with my fork (the upstream for this PR) supplying custom repositories for composer. Have a look at the composer docs here https://getcomposer.org/doc/05-repositories.md#loading-a-package-from-a-vcs-repository

Very helpful, @voydz. Thanks.

We'll handle this further in #101