开发者

doctrine2 - use custom query getter

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;
      }

   }
}


Take a look into https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/working-with-associations.html#filtering-collections

I believe that's what you've been looking for.


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:

// class Foo\Bundle\Repository\BarRepository
public function getCurrentVersion(MyClass $class)
{
    $dql = 'SELECT v FROM Namespace\Of\Version\Class v WHERE v.application_id=:id AND current=1';
    $query = $this->_em->createQuery($dql);
    $query->setParameter('id', $class->getId());
    $version = $query->execute();

    return $version;
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜