Typically when I use MySQL in raw PHP I only SELECT the fields I’m going to be using with that retrieved dataset; in high volume environments it makes sense to reduce the data transfer as much as possible.
It’s cool that Doctrine lets you define related objects so that, by adding a line or two to the entity definition, you can suddenly access Employee->Company->Fax. It seems (though I haven’t checked this) that behind the scenes it’s doing SELECT *. If this is true, is there a way to only pull the fields I think I’ll need? Or do you think it’s even an issue with a solid caching scheme?
Doctrine and Entity Manager, in symfony2, act much like as you described.
As you fetch an object from database, doctrine will do a
SELECT *for you.Moreover, if you want to access at some related properties via
foreign key, doctrine will use the lazy loading that means you haven’t to specify into the query how to retrieve some fields because doctrine alredy knows how. The best thing is that the query isn’t done since you call that field (good in conditional statement and so on)Returning to your question, you can retrieve only those fields that you’re interested in. First step is to define a
repositoryfor your class object. The second is to write a DQL query (Doctrine Query Language) to extract only “your” fields.Here’s an example where I have a class called
Userand a related repository calledUserRepositorywhere the “interesting” part is
@ORM\Entity(repositoryClass="CompanyName\UserBundle\Repository\UserRepository")Now the code for repository:
And you got what you want. For use that “custom” query, simply use that repository in the following way
where, of course,
emis an instance ofentity manager