我在创建查询时遇到问题,该查询应返回未分配给预算的成本中心。
数据库结构:
**Cost_center:**
+------+-----------+
| id | title |
+------+-----------+
| (PK) | (VARCHAR) |
+------+-----------+
\/
One
to
many
\/
**Budget_operation_scope_cost_center:**
+----------------+---------------------------+
| cost_center_id | budget_operation_scope_id |
+----------------+---------------------------+
| (FK) | (FK) |
+----------------+---------------------------+
\/
Many
to
one
\/
**Budget_operation_scope:**
+------+-----------+-----------+
| id | title | budget_id |
+------+-----------+-----------+
| (PK) | (VARCHAR) | (FK) |
+------+-----------+-----------+
\/
Many
to
one
\/
**Budget:**
+------+-------+
| id | year |
+------+-------+
| (PK) | (INT) |
+------+-------+
管理以执行返回分配到预算成本中心列表的查询:
$query = $this->getEntityManager()
->createQueryBuilder()
->select('costCenter')
->from('ResourcesBundle:CostCenter', 'costCenter')
->leftJoin('costCenter.budgetOperationScope', 'budgetOperationScope')
->where('budgetOperationScope.budgetId = :budget')
->setParameter('budget', $budget)
->getQuery()->getResult();
问题:如何获取未分配给预算的成本中心?
答案 0 :(得分:0)
此行过早地限制了您的查询,并有效地使您的左连接加入:
->where('budgetOperationScope.budgetId = :budget')
您可以将其移动到左连接中,如下所示:
->leftJoin('costCenter.budgetOperationScope', 'budgetOperationScope', 'WITH' 'budgetOperationScope.budgetId = :budget')
这样,当成本中心没有预算时,您将获得budgetOperationScope的空行。
所以你可以有效地做到:
->where('budgetOperationScope IS NULL')
所有在一起:
$query = $this->getEntityManager()
->createQueryBuilder()
->select('costCenter')
->from('ResourcesBundle:CostCenter', 'costCenter')
->leftJoin('costCenter.budgetOperationScope', 'budgetOperationScope', 'WITH' 'budgetOperationScope.budgetId = :budget')
->where('budgetOperationScope IS NULL')
->setParameter('budget', $budget)
->getQuery()->getResult();