[英]Symfony doctrine DQL random result in Query with MaxResult
How can I get a random result with an dql Query? 如何使用dql查询获得随机结果?
This is my query: 这是我的查询:
$firstCategoryId = 50;
$repository = $this->entityManager->getRepository(BaseProduct::class);
$products = $repository->createQueryBuilder('p')
->join('p.categories', 'c')
->where('c.id = :categoryId')
->setParameter('categoryId', $firstCategoryId)
->getQuery()
->setMaxResults(4)
->getResult();
This returns me always the first 4 products. 这总是返回前4种产品。 Lets say the category with ID 50 has over 100 products. 假设ID为50的类别有100多种产品。 And what I want is querying randomly 4 articles from category with ID 50. But how? 我想从ID为50的类别中随机查询4篇文章。但是如何? Is this possible? 这可能吗? Of course I can set no Max Result and than do it with PHP... but this is not a good solution because of performance. 当然,我不能设置Max Result,也不能使用PHP来设置Max Result ...但这不是一个很好的解决方案,因为它具有性能。
You need to create dql function for that. 您需要为此创建dql函数。 https://gist.github.com/Ocramius/919465 you can check that. https://gist.github.com/Ocramius/919465可以检查一下。
namespace Acme\Bundle\DQL;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
class RandFunction extends FunctionNode
{
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker)
{
return 'RAND()';
}
}
After that open your config.yml file and add autoload that RandFunction. 之后,打开您的config.yml文件并添加自动加载该RandFunction。
orm:
dql:
numeric_functions:
Rand: Acme\Bundle\DQL\RandFunction
And your query must be like: 您的查询必须类似于:
$firstCategoryId = 50;
$repository = $this->entityManager->getRepository(BaseProduct::class);
$products = $repository->createQueryBuilder('p')
->join('p.categories', 'c')
->addSelect('RAND() as HIDDEN rand')
->where('c.id = :categoryId')
->orderBy('rand')
->setParameter('categoryId', $firstCategoryId)
->getQuery()
->setMaxResults(4)
->getResult();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.