使用没有实体类的本机SQL查询 [英] Using native SQL query without entity class
问题描述
我需要使用几个工会和子查询来创建本机SQL查询。大概如下所示:
I need to create native SQL query with couple of unions and subqueries. It'll look approximately like this:
SELECT res.id, COUNT(*) as count_ids
FROM (
SELECT a.id FROM ... a WHERE ... LIKE ('%:param%')
UNION ALL
SELECT b.id FROM ... b WHERE ... LIKE ('%:param%')
UNION ALL
...
) res
GROUP BY res.id
ORDER BY count_ids asc
结果不符合我在应用程序中使用的任何实体。可以用匿名对象创建 ResultSetMapping
吗?或者至少可以创建一个不会在更新模式时创建表的实体,所以我可以将结果映射到它?
Result won't match any Entity I use in my application. Is it possible to create ResultSetMapping
with "anonymous" object? Or is it, at least, possible to create an Entity that wouldn't create table next time I update schema, so I can map results to it?
还是在那里任何其他教义友好的方式来处理这样的查询?对数据库进行更改是不可能的,因为我正在处理那些不能被触摸的遗留的东西。我也强烈希望如果我在数据库方面做了一切,而不涉及PHP中的大部分。
Or is there any other Doctrine-friendly way to deal with such query? Making changes to database isn't possible though, as I'm dealing with legacy stuff that cannot be touched. I'd also strongly prefer if I did everything on database side, not involving much of PHP in it.
推荐答案
你有特别需要将结果映射到域对象?如果没有,您可以使用DBAL进行一个简单的旧查询,这将返回一个数组,详见 Symfony2食谱和 Doctrine DBAL文档:
Do you have a particular need to map results to a domain object? If not, you could use the DBAL to make a plain old query, which will return an array, as detailed in the Symfony2 cookbook and the Doctrine DBAL documentation:
$conn = $this->container->get('database_connection');
$sql = 'SELECT res.id, COUNT(*)...';
$rows = $conn->query($sql);
这篇关于使用没有实体类的本机SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!