Finding Entities in Symfony 3 Using Doctrine
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.
Background
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 Entity
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.
Test Data
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:
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows