在 Repository 中使用 Doctrine 2 ORM 和 OneToOne 获得 "rank"
Obtain "rank" using Doctrine 2 ORM and OneToOne in Repository
我发现几乎不可能达到我想要的结果,在这里和其他网站上找到了不同的解决方案(子查询、原始查询等)尝试了这么多次之后,我必须问这个问题。
我的目标是 extract/get 每个 "projects" 排名基于他们的 "score"。
将 "score" 视为 int 并具有 1,2,6,4,8,10,200 等值
排名是这样的:
排名 - 得分
- 200
- 10
- 8
- 6
为了让我的问题尽可能简单明了,我将我的实际 tables/entities 重命名如下:
MainEntity (main_table):
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
// other fields, un-related to this question
/**
* @ORM\OneToOne(targetEntity="Application\Entity\SecondTable", mappedBy="second_table_data")
*/
protected $second_table;
/**
* @ORM\OneToOne(targetEntity="Application\Entity\ThirdTable", mappedBy="third_table_data")
*
*/
protected $third_table;
SecondEntity (second_table):
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
// other fields, un-related to this question
/**
* @ORM\OneToOne(targetEntity="Application\Entity\SecondTable", inversedBy="second_table")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $second_table_data;
ThirdEntity (third_table):
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
// other fields, un-related to this question
/**
* @ORM\Column(name="score")
*/
protected $score;
/**
* @ORM\OneToOne(targetEntity="Application\Entity\ThirdTable", inversedBy="third_table")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $third_table_data;
存储库函数 select "all projects" 按分数排序:
public function findAllProjects()
{
$entityManager = $this->getEntityManager();
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder->select('u')
->from(MainEntity::class, 'u')
->leftJoin('u.third_table', 't')
->orderBy('t.score', 'DESC');
return $queryBuilder->getQuery()->getResult();
}
这很好用(我相信),因为我从 main_table + second_table[ 得到了所有 "projects" =62=] + third_table 基于他们的 "project_id".
但问题是我无法找到正确计算或获取每个项目的 "rank" 编号的方法。我还尝试使用 "foreach" 并将 "index" 用作 "rank" 但这将无法正常工作,因为我使用的是 ORMPaginator 所以每次你单击 "page","foreach" "index" 将从 0 重置。
我希望问题足够清楚,让您清楚地了解我的问题。
请指教我怎样才能做到这一点,如果我的整个方法是错误的,请指出。
每个 advice/hint/solution 都受到高度赞赏。
首先,真正注意列类型。
您的所有专栏都是按照学说创建的 varchar(255)
,如果您希望在这些专栏上创建 order by
,那么这不是理想的选择。这是 vendor/bin/doctrine-module orm:schema-tool:create --dump-sql
:
的输出片段
CREATE TABLE main_entity (
id VARCHAR(255) NOT NULL,
PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
因此,您必须做的第一件事是向您的列添加列类型:
/**
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue
*/
protected $id;
我使用了这个数据:
third_table main_entity
+----+------------+-------+ +----+
| id | project_id | score | | id |
+----+------------+-------+ +----+
| 1 | 1 | 8 | | 1 |
| 2 | 2 | 10 | | 2 |
| 3 | 3 | 6 | | 3 |
| 4 | 4 | 200 | | 4 |
+----+------------+-------+ +----+
关于排名,基本上是行号,SQL 查询是:
SELECT
ROW_NUMBER() OVER (ORDER BY t.score DESC) AS r_rank,
t.score AS score
FROM main_entity m
LEFT JOIN third_table t ON m.id = t.project_id
ORDER BY t.score DESC
-- LIMIT 2 OFFSET 2 -- Limits for pagination
without limits with limits
+--------+-------+ +--------+-------+
| r_rank | score | | r_rank | score |
+--------+-------+ +--------+-------+
| 1 | 200 | | 3 | 8 |
| 2 | 10 | | 4 | 6 |
| 3 | 8 | +--------+-------+
| 4 | 6 |
+--------+-------+
不幸的是,ROW_NUMBER
没有为 SQL 查询实现。如果你试试这个:
$queryBuilder->select(['ROW_NUMBER() OVER (ORDER BY t.score DESC)','t.score'])
->from(MainEntity::class, 'u')
->leftJoin('u.third_table', 't')
->orderBy('t.score', 'DESC');
$queryBuilder->getQuery()->getResult();
您将收到以下错误:[Syntax Error] line 0, col 7: Error: Expected known function, got 'ROW_NUMBER'
替代方案可以是:
$sql = 'SELECT
ROW_NUMBER() OVER (ORDER BY t.score DESC) AS r_rank,
t.score AS score
FROM main_entity m
LEFT JOIN third_table t ON m.id = t.project_id
ORDER BY t.score DESC';
$results = $this->entityManager->getConnection()->executeQuery($sql);
我看到分页器步行者中有类似的东西(?!),但并非所有数据库都支持它们,as you can see in the walker itself:
public function walkSelectStatement(SelectStatement $AST)
{
if ($this->platformSupportsRowNumber()) {
return $this->walkSelectStatementWithRowNumber($AST);
}
return $this->walkSelectStatementWithoutRowNumber($AST);
}
private function platformSupportsRowNumber()
{
return $this->platform instanceof PostgreSqlPlatform
|| $this->platform instanceof SQLServerPlatform
|| $this->platform instanceof OraclePlatform
|| $this->platform instanceof SQLAnywherePlatform
|| $this->platform instanceof DB2Platform
|| (method_exists($this->platform, 'supportsRowNumberFunction')
&& $this->platform->supportsRowNumberFunction());
}
作为最后的机会,您可以 'add' 自己建立索引,甚至可以使用分页器。
如果你知道页面大小和当前页面,你可以计算排名:
$pageSize = 2;
$currentPage = 1;
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('t.score') // Here I use only the t.score, but you could put the whole class
->from(MainEntity::class, 'u')
->leftJoin('u.third_table', 't')
->orderBy('t.score', 'DESC');
$queryBuilder->setMaxResults($pageSize);
$queryBuilder->setFirstResult(($currentPage - 1) * $pageSize);
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($queryBuilder->getQuery());
$adapter = new \DoctrineORMModule\Paginator\Adapter\DoctrinePaginator($paginator);
$results = [];
$currentItem = 1 + ($currentPage - 1) * $pageSize;
foreach($adapter->getPaginator()->getIterator()->getArrayCopy() as $result){
$results[] = [
'rank' => $currentItem++,
'item' => $result
];
}
var_dump($results);
结果:
$pageSize = 2; $pageSize = 2;
$currentPage = 1; $currentPage = 2;
Array Array
( (
[0] => Array [0] => Array
( (
[rank] => 1 [rank] => 3
[item] => Array [item] => Array
( (
[score] => 200 [score] => 8
) )
) )
[1] => Array [1] => Array
( (
[rank] => 2 [rank] => 4
[item] => Array [item] => Array
( (
[score] => 10 [score] => 6
) )
) )
) )
我发现几乎不可能达到我想要的结果,在这里和其他网站上找到了不同的解决方案(子查询、原始查询等)尝试了这么多次之后,我必须问这个问题。
我的目标是 extract/get 每个 "projects" 排名基于他们的 "score"。
将 "score" 视为 int 并具有 1,2,6,4,8,10,200 等值
排名是这样的:
排名 - 得分
- 200
- 10
- 8
- 6
为了让我的问题尽可能简单明了,我将我的实际 tables/entities 重命名如下:
MainEntity (main_table):
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
// other fields, un-related to this question
/**
* @ORM\OneToOne(targetEntity="Application\Entity\SecondTable", mappedBy="second_table_data")
*/
protected $second_table;
/**
* @ORM\OneToOne(targetEntity="Application\Entity\ThirdTable", mappedBy="third_table_data")
*
*/
protected $third_table;
SecondEntity (second_table):
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
// other fields, un-related to this question
/**
* @ORM\OneToOne(targetEntity="Application\Entity\SecondTable", inversedBy="second_table")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $second_table_data;
ThirdEntity (third_table):
/**
* @ORM\Id
* @ORM\Column(name="id")
* @ORM\GeneratedValue
*/
protected $id;
// other fields, un-related to this question
/**
* @ORM\Column(name="score")
*/
protected $score;
/**
* @ORM\OneToOne(targetEntity="Application\Entity\ThirdTable", inversedBy="third_table")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $third_table_data;
存储库函数 select "all projects" 按分数排序:
public function findAllProjects()
{
$entityManager = $this->getEntityManager();
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder->select('u')
->from(MainEntity::class, 'u')
->leftJoin('u.third_table', 't')
->orderBy('t.score', 'DESC');
return $queryBuilder->getQuery()->getResult();
}
这很好用(我相信),因为我从 main_table + second_table[ 得到了所有 "projects" =62=] + third_table 基于他们的 "project_id".
但问题是我无法找到正确计算或获取每个项目的 "rank" 编号的方法。我还尝试使用 "foreach" 并将 "index" 用作 "rank" 但这将无法正常工作,因为我使用的是 ORMPaginator 所以每次你单击 "page","foreach" "index" 将从 0 重置。
我希望问题足够清楚,让您清楚地了解我的问题。
请指教我怎样才能做到这一点,如果我的整个方法是错误的,请指出。
每个 advice/hint/solution 都受到高度赞赏。
首先,真正注意列类型。
您的所有专栏都是按照学说创建的 varchar(255)
,如果您希望在这些专栏上创建 order by
,那么这不是理想的选择。这是 vendor/bin/doctrine-module orm:schema-tool:create --dump-sql
:
CREATE TABLE main_entity (
id VARCHAR(255) NOT NULL,
PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
因此,您必须做的第一件事是向您的列添加列类型:
/**
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue
*/
protected $id;
我使用了这个数据:
third_table main_entity
+----+------------+-------+ +----+
| id | project_id | score | | id |
+----+------------+-------+ +----+
| 1 | 1 | 8 | | 1 |
| 2 | 2 | 10 | | 2 |
| 3 | 3 | 6 | | 3 |
| 4 | 4 | 200 | | 4 |
+----+------------+-------+ +----+
关于排名,基本上是行号,SQL 查询是:
SELECT
ROW_NUMBER() OVER (ORDER BY t.score DESC) AS r_rank,
t.score AS score
FROM main_entity m
LEFT JOIN third_table t ON m.id = t.project_id
ORDER BY t.score DESC
-- LIMIT 2 OFFSET 2 -- Limits for pagination
without limits with limits
+--------+-------+ +--------+-------+
| r_rank | score | | r_rank | score |
+--------+-------+ +--------+-------+
| 1 | 200 | | 3 | 8 |
| 2 | 10 | | 4 | 6 |
| 3 | 8 | +--------+-------+
| 4 | 6 |
+--------+-------+
不幸的是,ROW_NUMBER
没有为 SQL 查询实现。如果你试试这个:
$queryBuilder->select(['ROW_NUMBER() OVER (ORDER BY t.score DESC)','t.score'])
->from(MainEntity::class, 'u')
->leftJoin('u.third_table', 't')
->orderBy('t.score', 'DESC');
$queryBuilder->getQuery()->getResult();
您将收到以下错误:[Syntax Error] line 0, col 7: Error: Expected known function, got 'ROW_NUMBER'
替代方案可以是:
$sql = 'SELECT
ROW_NUMBER() OVER (ORDER BY t.score DESC) AS r_rank,
t.score AS score
FROM main_entity m
LEFT JOIN third_table t ON m.id = t.project_id
ORDER BY t.score DESC';
$results = $this->entityManager->getConnection()->executeQuery($sql);
我看到分页器步行者中有类似的东西(?!),但并非所有数据库都支持它们,as you can see in the walker itself:
public function walkSelectStatement(SelectStatement $AST)
{
if ($this->platformSupportsRowNumber()) {
return $this->walkSelectStatementWithRowNumber($AST);
}
return $this->walkSelectStatementWithoutRowNumber($AST);
}
private function platformSupportsRowNumber()
{
return $this->platform instanceof PostgreSqlPlatform
|| $this->platform instanceof SQLServerPlatform
|| $this->platform instanceof OraclePlatform
|| $this->platform instanceof SQLAnywherePlatform
|| $this->platform instanceof DB2Platform
|| (method_exists($this->platform, 'supportsRowNumberFunction')
&& $this->platform->supportsRowNumberFunction());
}
作为最后的机会,您可以 'add' 自己建立索引,甚至可以使用分页器。
如果你知道页面大小和当前页面,你可以计算排名:
$pageSize = 2;
$currentPage = 1;
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('t.score') // Here I use only the t.score, but you could put the whole class
->from(MainEntity::class, 'u')
->leftJoin('u.third_table', 't')
->orderBy('t.score', 'DESC');
$queryBuilder->setMaxResults($pageSize);
$queryBuilder->setFirstResult(($currentPage - 1) * $pageSize);
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($queryBuilder->getQuery());
$adapter = new \DoctrineORMModule\Paginator\Adapter\DoctrinePaginator($paginator);
$results = [];
$currentItem = 1 + ($currentPage - 1) * $pageSize;
foreach($adapter->getPaginator()->getIterator()->getArrayCopy() as $result){
$results[] = [
'rank' => $currentItem++,
'item' => $result
];
}
var_dump($results);
结果:
$pageSize = 2; $pageSize = 2;
$currentPage = 1; $currentPage = 2;
Array Array
( (
[0] => Array [0] => Array
( (
[rank] => 1 [rank] => 3
[item] => Array [item] => Array
( (
[score] => 200 [score] => 8
) )
) )
[1] => Array [1] => Array
( (
[rank] => 2 [rank] => 4
[item] => Array [item] => Array
( (
[score] => 10 [score] => 6
) )
) )
) )