10.
Raw SQL Queries
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Whoops, an error! Please, try again later.
4 Comments
How would the code change if you would want to return array of objects of CategoryFortuneStats?
Would you have a foreach loop in repository?
Something like
?
Hey @Peter-K
There are a few ways to do that. The first and most complex is by using the
ResultSetMappingof Doctrine. Here's the docs: https://www.doctrine-project.org/projects/doctrine-orm/en/3.2/reference/native-sql.htmlA second approach would be using the
NEWstatement in your query, but I believe it only works with DTOs, let me know if I'm wrong - here's more info about it https://dev.to/jszutkowski/fast-way-to-create-dto-using-doctrine-2dlfLastly, my preferred way, using two queries. First I'll write that complex, raw query and only fetch the entity ids, then in a second query, I fetch the entity objects by id. It's not the most performant way but it's way simpler
Cheers!
Hello, I have a complex query with multiple joins and would like to use a raw query. I also have multiple schemas. When I setup up my connection in my repository is there a way to specify the the schema so it the connection does not use the default? Thank you in advance.
Heya @Brent-M!
Sorry for the slow reply! I'm far from an expert on this topic. However, my impression is that:
A) Each entity belongs to one specific entity manager
B) Each entity manager belong to one specific connection
So if you're inside of a repository for an entity, then there should only be one "connection" that for that entity. However, I still think your question is valid: you could put a query in a repository that, perhaps, talks to totally different tables.
To get another connection, what you need is the manager registry - and that is actually injected into your repository already - https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository. So, you could tweak the
__construct()of your repository to store this registry on a property, then grab the connection from that when you need it -$this->registry->getConnection('specify schema').Let me know if that helps!
Cheers!
"Houston: no signs of life"
Start the conversation!