The other day I ran into an interesting case trying to get data out of a Symfony project where the entities I was interested in were dependent on a second entity but I couldn’t find an easy way to find them without multiple queries. It took me a lot of reading through Stack Overflow questions to find the results but I wanted to document what I’ve found.
Please note I wrote this using Symfony 3.2.3. Last time I posted something about Symfony someone asked me to mention this.
In this example, I have a super basic ticketing system. There’s a Ticket entity and a Ticket Entry entity that keeps track of when people update the tickets.
Ticket Entry Entity
The Ticket Entry class is listed below. The two piece of information I would like to highlight are the user attribute which is a text representation of the user who made the change (text because it keeps the examples easier to understand) and the created attribute which keeps track of when the entry was added.
Now we need to create some example data. We’re going to create three tickets each with an entry.
Find By ID
Now we can talk about how to search. The most basic example is to search based on the entity’s ID column:
Find By Another Field
An amazing feature of Doctrine is it’s ability to allow you to search based on another field inside the entity. For example, we can find the ticket whose name is ‘ticket2’:
Find With a Join
This is the part I spend ran into some trouble, what if we’re curious about all the tickets that were entered by ‘scott’ (so you don’t have to scroll back up it’s ticket1 and ticket2).
The solution to this is to do a join and then you’ll get the correct results:
I learned the hard way that you must define the parameters and then set them.
You can also search by date:
Like this post? Don't forget to follow us on Twitter and Facebook for updates.