Search code examples
mappingdoctrine-ormdql

Query or read only properties in doctrine 2


I am looking to create a property on an entity that will primarily be use to hold count. Example:

Brand
- id
- name
- numberOfProducts

The numberOfProducts property is nothing more than a count of products. However, this count changes depending on how i look at the product. For instance, maybe i only want the count of active products for that brand vs the count of all products for that brand.

nHibernate has something similar, see: Query Unmapped Columns in NHibernate

Is this possible? Or is there a better way of solving my problem? I could of course add 2 count properties for each situation then add a denormalized field but this is a lot of work for a case that is more or less a one time use.

I could also simply create to grab all brands as well as the count query all in one DQL statement, however this would mean i have to manually map the counted field into the property. I was hoping doctrine could just do that mapping for me.


Solution

  • I think the best solution here would be to create custom hydrators, that are able to set extra (non managed fields) into entity properties:

    http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/dql-doctrine-query-language.html#custom-hydration-modes