我不会尝试在只有一个查询中获得所需的结果。这太复杂了,你会花很多时间来尝试得到你想要的。
首先,我假设您希望得到一个 排序的 数组 Service 实体,如下所示:
/** @var Service[] $results **/
$results = $this->getDoctrine()->getManager()->getRepository('YourBundle:YourServiceRepo')->findSerivesByGivenSerchCriteria($yourConditions);
所以你可以简单地迭代(foreach)它
如果是这样,请考虑以下几点:
- 在您的服务存储库中创建三个单独的方法以获取
- 标题中包含搜索条件的服务 - 第一优先
- 标签中包含搜索条件的服务 - 第二优先
- 描述中包含 serach-criteria 的服务 - 第三优先级
在你的findSerivesByGivenSearchCriteria()method 中,你调用了所有三个,并且可以按照我想要的任何顺序组合找到的结果
例如:
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;
}
要获得“独特性”,请尝试结合 Doctrine 的 INDEX BY 和 HIDDEN
INDEX BY -> http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#using-index-by
INDEX BY 在 QueryBuilder -> https://stackoverflow.com/a/15120793/348193
HIDDEN -> https://michelsalib.com/2012/03/04/doctrine2-ninja-with-the-hidden-keyword/
为什么我不会选择UNION的方式?
由于您使用 symfony 和教义 UNION 不是最好的方法。见How to write UNION in Doctrine 2.0
如您所见,UNION Doctrine 不支持,您必须使用 NativeQuery(这可能会令人沮丧 ResultSetMappingBuilder 和修正映射并将原始结果转换为到所需的实体)