在存储库中使用Doctrine 2 ORM和OneToOne获得“等级”

问题描述 投票:0回答:1

我发现在这里和其他网站上使用不同的解决方案(子查询,原始查询等)进行了无数次尝试之后,我几乎无法达到我想要的结果,我必须问这个问题。

我的目标是根据每个“项目”的“得分”来提取/获得它们的排名。

将“分数”视为int并使用1,2,6,4,8,10,200等值)>

排名将是这样:

排名-得分

  1. 200
  2. 10
  3. 8
  4. 6
  5. 为了使我的问题尽可能简单明了,我将实际的表/实体重命名为以下名称:

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;

以及存储库功能来选择按其得分排序的“所有项目”:

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();
}

[这很好(我相信),因为我基于它们的“ project_id”从main_table

+ second_table + third_table中获取了所有“项目”。

但是问题是我找不到正确计算或获得每个项目的“等级”数字的方法。我也尝试使用“ foreach”并将“ index”用作“ rank”,但是由于我正在使用ORMPaginator

,因此无法正常工作,因此每次单击“ foreach”“ index”的“页面”时,将从0重置。

我希望这个问题足够清楚,并让您对我的问题有清楚的了解。

请告知我该如何实现,如果我的整体方法不正确,请指出。

每一个建议/提示/解决方案都受到高度赞赏。

我发现在这里和其他网站上使用不同的解决方案(子查询,原始查询等)进行了无数次尝试之后,几乎无法达到我想要的结果,我必须问这个问题。 ...

php zend-framework doctrine-orm doctrine zend-framework3
1个回答
0
投票

您可以尝试为此https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html使用窗口功能像]

SELECT score, RANK()  OVER w AS 'rank',
       FROM table
       WINDOW w AS (PARTITION BY project_id ORDER BY score DESC);
© www.soinside.com 2019 - 2024. All rights reserved.