Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Symfony-用于获取基于父节点的子节点计数的索引_Php_Symfony_Query Builder - Fatal编程技术网

Php Symfony-用于获取基于父节点的子节点计数的索引

Php Symfony-用于获取基于父节点的子节点计数的索引,php,symfony,query-builder,Php,Symfony,Query Builder,我有一个查询,它给了我一组“公司”(以变量$companys表示),还有一个查询返回先前获取的公司(以$companys表示)存在的子公司数。查询结果是准确的,但我很难知道哪个“childCount”属于哪个公司 以下是公司名单 array:3 [▼ 0 => Company {#707 ▶} 1 => Company {#720 ▶} 2 => Company {#723 ▶} ] 下面给出了返回计数的查询结果 array:2 [▼ 0 => arra

我有一个查询,它给了我一组“公司”(以变量$companys表示),还有一个查询返回先前获取的公司(以$companys表示)存在的子公司数。查询结果是准确的,但我很难知道哪个“childCount”属于哪个公司

以下是公司名单

array:3 [▼
  0 => Company {#707 ▶}
  1 => Company {#720 ▶}
  2 => Company {#723 ▶}
]
下面给出了返回计数的查询结果

array:2 [▼
  0 => array:1 [▼
    "childCount" => "3"
  ]
  1 => array:1 [▼
    "childCount" => "1"
  ]
]
注:三分之一的公司没有子公司

//$companies variable has list of companies for which we have to find child companies

 public function getSubCompanies($companies)
    {
        $queryBuilder = $this->getEntityManager()->createQueryBuilder();
        $queryBuilder
                    ->select('count(c) as childCount')
                    ->from('AppBundle:Company','c','c.id')
                    ->where('c.parentId IN (:parentId)')
                    ->setParameter('parentId',$companies)
                    ->addGroupBy('c.parentId')

        ;

        return $queryBuilder->getQuery()->getResult();
    }
我希望将默认索引(0和1)替换为母公司id,如下所示

array:2 [▼
  parentCompanyId1 => array:1 [▼
    "childCount" => "3"
  ]
  parentCompanyId2 => array:1 [▼
    "childCount" => "1"
  ]
]

->之后选择
,只需添加更多信息,如

->addSelect('c.parentId')
结果数组应该是这样的(我显然不知道您的parentID):

要将其转换为适当的格式,请执行以下操作:

$result = [];
foreach($queryResult as $row) {
    $result[$row['parentId']] = $row; 
    // maybe even unset the parentId afterwards ...
}

为了解决这个问题,我定义了一个实体“children”,它与同一个表“Company”有一个OneToMany关系,并由“parentId”映射

一家公司: 儿童: 目标实体:AppBundle\Entity\Company mappedBy:parentId 级联:[“持久化”]


子公司的数量给了我一个表中子公司的数量,如果有人需要更清晰的解决方案,我会发布额外的代码。感谢您帮助@Jakumi和@Cerad

从查询中准确获取所需信息将有点困难,但只需将parentId添加到select语句中即可获得所需信息。之后,如果你真的需要你想要的格式,那么使用一点php来转换结果。是的,我同意这个解决方案,但是它涉及到通过queryResult的循环。我正在检查一种方法,以便在查询运行后立即获得所需的结果。谢谢你的想法。@ARIFAK稍微不那么有趣了一点。。。但是你可以试着做一些像这样的事情:
$result = [];
foreach($queryResult as $row) {
    $result[$row['parentId']] = $row; 
    // maybe even unset the parentId afterwards ...
}