I would not try get the desired results in only one query. It will be too complicated and you'll spent to much time trying get what you want.
First, I assume you'd like to get a sorted Array of Service
entities like this:
/** @var Service[] $results **/
$results = $this->getDoctrine()->getManager()->getRepository('YourBundle:YourServiceRepo')->findSerivesByGivenSerchCriteria($yourConditions);
so you can simply iterate (foreach) through it
If it's the case, concider following:
- create three separate methods whitin your service-repository to get
- services with search-criteria in their title - first priority
- services with search-criteria in their tags - second priority
- services with serach-criteria in their desc - third priority
and in your findSerivesByGivenSearchCriteria()
method you call all three of them and could combine the found results in any order i'd like
for Example:
public function findSerivesByGivenSerchCriteria( $searchTirm ) {
$foundServicesByTitle = $this->findServicesBySearchCriteriaInTitle( $searachTirm );
$foundServicesByTag = $this->findServicesBySearchCriteriaInTags( $searchTirm );
$foundServicesByDesc = $this->findServicesBySearchCriteriaInDesc( $searchTirm );
// Hier you can combine found results in any order
$results = [];
if( false === empty($foundServicesByTitle ) )
{
// for example with array_merge ...
// NOTE: If you choose array_merge() you have to make sure your $foundServicesByTitle, $foundServicesByTag, $foundServicesByDesc have unique array-indexes
// And you get Results like
// array( 'unique_id_1' => ServiceEntity, 'unique_id_2' => ServiceEntity ... )
$results = array_merge($results, $foundServicesByTitle);
}
// .. do the same with other two
return $results;
}
To get the "uniqness" try to combine Doctrine's INDEX BY
and HIDDEN
INDEX BY
-> http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#using-index-by
INDEX BY
in QueryBuilder -> https://stackoverflow.com/a/15120793/348193
HIDDEN
-> https://michelsalib.com/2012/03/04/doctrine2-ninja-with-the-hidden-keyword/
Why I wouldn't choose the UNION
way?
Since you work with symfony and doctrine UNION
isn't the best way. See How to write UNION in Doctrine 2.0
As you can see, UNION
isn't supported by Doctrine and you have to use NativeQuery
(which could be frustrating with ResultSetMappingBuilder
and corect mapping and turning raw-results in to desired entities)