I’m using Symfony2 and Doctrine2. How would I go about using a different query for a get method? (poorly worded, let me explain)
i.e. I have an application entity, this has a one to many relation with Version
so in my application entity I have:
/**
* Get versions
*
* @return Doctrine\Common\Collections\Collection
*/
public function getVersions()
{
return $this->versions;
}
This is all good, however, how can I implement a method, such as
getCurrentVersion, where I perform a simple query, such as:
SELECT v.* FROM version WHERE application_id = 1 AND current = 1
and so in a twig template, I can do:
{% for application in applications %}
Name : {{ application.name }}
Current Version: {{ application.getCurrentVersion }}
{% endfor %}
Any help is much appreciated.
p.s. if i’m going about this wrong, please enlighten me.
Thanks.
EDIT: http://www.doctrine-project.org/docs/orm/2.1/en/reference/limitations-and-known-issues.html#join-columns-with-non-primary-keys Seriously?!
EDIT, I really don’t want to do this, it is unnecessary and resourcefully wasteful:
public function getCurrentVersion
{
foreach($this->versions as $version)
{
if($version->current)
{
return $version;
}
}
}
First, you shouldn’t touch the database from your entity. It’s considered bad practice to inject an entity manager into a managed entity, and it has no way of knowing about the data layer otherwise.
To do what you’re asking, you can use a custom entity repository with a getCurrentVersion method that takes an id or instance of the entity and runs the query on it:
Note that if you’re only expecting one version, you can use
$query->getSingleResult();instead of$query->execute();However, it sounds like you’re trying to do versioning/history on some of your classes, in which case, you should check out the Gedmo DoctrineExtensions and associated Symfony2 bundle; specifically, have a look at the Loggable behavioral extension, which handles versioning of your entities transparently.