我正在使用 Symfony 6 和 API 平台,在使用计算连接表的列对我的实体进行排序时遇到了一些困难。
这是表格
公司
+----+------------+--------------+--------------+
| id | name | industry | location |
+----+------------+--------------+--------------+
| 1 | TechCorp | Technology | New York |
| 2 | HealthPlus | Healthcare | San Francisco|
+----+------------+--------------+--------------+
开幕
+----+------------+-------------------+-----------+
| id | company_id | title | positions |
+----+------------+-------------------+-----------+
| 1 | 1 | Software Engineer | 1 |
| 2 | 1 | Data Scientist | 5 |
| 3 | 2 | Nurse | 2 |
| 4 | 2 | Teacher | 1 |
| 5 | 1 | Administrator | 5 |
| 6 | 1 | Administrator | 5 |
+----+------------+-------------------+-----------+
我想按职位数量显示公司,所以我做了这个查询
SELECT c.*, SUM(o.positions) AS 'job_positions'
FROM hira_db.company c
LEFT JOIN hira_db.opening o ON o.company_id = c.id
GROUP BY c.id
ORDER BY job_positions DESC
所以它会生成这样的东西
+----+------------+--------------+--------------+---------------+
| id | name | industry | location | job_positions |
+----+------------+--------------+--------------+---------------+
| 1 | TechCorp | Technology | New York | 16 |
| 2 | HealthPlus | Healthcare | San Francisco| 3 |
+----+------------+--------------+--------------+---------------+
但是当将相同的查询应用于学说时,它会弄乱分页计数
我做了一个 DoctrineExtension 并添加了这些查询
$alias = $queryBuilder->getRootAliases()[0];
$queryBuilder
->innerJoin(sprintf('%s.openings', $alias), 'job')
->addSelect('SUM(job.positions) AS HIDDEN job_positions')
->orderBy('job_positions', 'DESC')
->addGroupBy(sprintf('%s.id', $alias));
// default join column generated automatically by doctrine?
$queryBuilder->addGroupBy('openings_a1.id');
这回来了
{
"@context": "/api/contexts/Company",
"@id": "/api/companies",
"@type": "hydra:Collection",
"hydra:totalItems": 6,
而不是
{
"@context": "/api/contexts/Company",
"@id": "/api/companies",
"@type": "hydra:Collection",
"hydra:totalItems": 2,
我只有2家公司和6个职位空缺
您在查询生成器中使用 inner join,在 SQL 请求中使用 left join ;)