搜索并不那么昂贵,人们会在一个搜索查询中只搜索几个位置。
所以我要做的第一件事就是加载所有搜索到的位置的 id 以及它们所有父母的 id。
获取父母的身份证: BaseTreeFacade::getPathIds
public function getPathIds($entity)
{
$ids = $this->getPathQueryBuilder($entity)
->select('node.id')
->getQuery()
->getResult(AbstractQuery::HYDRATE_SCALAR);
return array_map('current', $ids);
}
此方法返回带有 id 的简单数组。现在我必须将搜索查询中的 id 与父母的 id 连接起来。
扩展 ID: Helpers::expandTreeValues
public static function expandTreeValues(BaseTreeFacade $facade, array $values)
{
$result = [];
foreach ($values as $id) {
$entity = $facade->findOneById($id);
$result[] = [$id];
$result[] = $facade->getPathIds($entity);
}
$result = call_user_func_array('array_merge', $result);
$result = array_unique($result, SORT_NUMERIC);
return $result;
}
下一步是创建 where 子句以在位置及其子项中进行搜索。
创建 where 子句: Helpers::prepareWhereClauseForChildren
public static function prepareWhereClauseForChildren(BaseTreeFacade $facade, array $values)
{
$where = [];
$parameters = [];
foreach ($values as $id) {
$entity = $facade->findOneById($id);
$where[] = "(l.lvl > :level$id AND l.id > :left$id AND l.id < :right$id)";
$parameters["left$id"] = $entity->lft;
$parameters["right$id"] = $entity->rgt;
$parameters["level$id"] = $entity->lvl;
}
$where = implode(' OR ', $where);
return (object) [
'where' => $where === '' ? null : $where,
'parameters' => count($parameters) === 0 ? null : $parameters,
];
}
由于树的左右分支,我可以在所有子位置中搜索。最后一步是使用上一步创建的 where 子句更新原始 QueryBuilder。
完成 QueryBuilder: Helpers::updateWithTreeEntity
public static function updateWithTreeEntity(QueryBuilder $qb, array $values, $addWhere = null, array $addParameters = null)
{
if ($addParameters === null) {
$addParameters = [];
}
$addParameters['locations'] = $values;
$appendQuery = $addWhere === null ? '' : " OR $addWhere";
$qb->andWhere("l.id IN (:locations)$appendQuery");
foreach ($addParameters as $key => $value) {
$qb->setParameter($key, $value);
}
}
用法示例:
public function createQueryBuilderForSearchingInLocations(array $locations)
{
$gb = $this->createQueryBuilderSomehow();
$facade = $this->getLocationsFacadeSomehow();
$locations = Helpers::expandTreeValues($facade, $locations);
$where = Helpers::prepareWhereClauseForChildren($facade, $locations);
Helpers::updateWithTreeEntity($qb, $locations, $where->where, $where->parameters);
return $qb;
}