5

I have an overview with a search field. The query should search on both the title and description, but I would want to show my results that have the search parameter in the title first in the list. I am using a QueryInterface and have following condition group

 $group = $query->orConditionGroup();
 $group->condition('title', "%" . $searchString . "%", 'LIKE');
 $group->condition('field_description', "%" . $searchString . "%", 'LIKE');
 $query->condition($group);

Does anyone know a way to use a groupBy in a QueryInterface to do something like this

ORDER BY
(title LIKE "%" . $searchString . "%") DESC,
(field_description LIKE "%" . $searchString . "%") DESC;
5
  • Not sure it's the most efficient, but this is one outline way to do it: use $query->addTag('foo');, then implement hook_query_foo_alter() to get access to the regular query once it's been built. From there you can add CASE expressions for your fields (example here), then use $query->orderBy with those added expressions
    – Clive
    Jul 7, 2023 at 20:08
  • As a slight aside, it'd be a good idea to inject the database service and use its escapeLike method on $searchString. Without it, if someone searches for a string with a % character you're risking an SQL error or at least inaccurate results
    – Clive
    Jul 7, 2023 at 20:37
  • condition() is for WHERE clauses, which have a different effect than ORDER BY. ORDER BY would then not show first the rows for which the desired value is found in the title and then the rows for which the same value is found in a field description.
    – apaderno
    Jul 9, 2023 at 7:19
  • @Clive Can i use my variable $searchstring in this hook? Jul 12, 2023 at 6:56
  • I don't think there's a way to pass it through, but anything you can declare in your current context you can also declare in the hook (or define a service to give you that data if you use it in more than one place)
    – Clive
    Jul 12, 2023 at 20:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.