我在 postgresql 上配置了一个 symfony/doctrine 项目,我想获得表中某个元素的随机结果。我怎样才能做到这一点?
<?php
// App/Doctrine/DBAL/FunctionNode/Random.php
namespace App\Doctrine\DBAL\FunctionNode;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
/**
* RandFunction ::= "RANDOM" "(" ")".
*/
final class Random extends FunctionNode
{
public function parse(\Doctrine\ORM\Query\Parser $parser): void
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker): string
{
return 'RANDOM()';
}
}
# config/packages/doctrine.yaml
doctrine:
# ...
orm:
dql:
numeric_functions:
Random: App\Doctrine\DBAL\FunctionNode\Random
使用示例
<?php
// App\Repository\EntityRepository.php
namespace App\Repository;
class EntityRepository extends ServiceEntityRepository
{
// ...
public function getOneRandom()
{
return = $this->createQueryBuilder('alias')
->orderBy('RANDOM()')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult()
;
}
}
<?php
namespace App\DQL;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\TokenType;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
class RandomFunction extends FunctionNode {
/**
* @param \Doctrine\ORM\Query\Parser $parser
*
* @return void
* @throws \Doctrine\ORM\Query\QueryException
*/
final public function parse(Parser $parser): void {
$parser->match(TokenType::T_IDENTIFIER);
$parser->match(TokenType::T_OPEN_PARENTHESIS);
$parser->match(TokenType::T_CLOSE_PARENTHESIS);
}
final public function getSql(SqlWalker $sqlWalker): string {
return 'RANDOM()';
}
}
# config/packages/doctrine.yaml
doctrine:
dql :
numeric_functions:
Random: App\DQL\RandomFunction