如何从实体获取反应物? [英] How to get a Respository from an Entity?

查看:103
本文介绍了如何从实体获取反应物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体名为游戏与相关的存储库名为 GameRepository

I have an Entity called Game with a related Repository called GameRepository:

/**
 * @ORM\Entity(repositoryClass="...\GameRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Game {
    /**
     * @ORM\prePersist
     */
    public function setSlugValue() {
        $this->slug = $repo->createUniqueSlugForGame();
    }
}

在prePersist方法中,我需要确保Game's slug字段是唯一的,它需要一个数据库查询。要查询,我需要访问 EntityManager 。我可以从GameRepository里面获取EntityManager。所以:如何从游戏中获取GameRespository?

In the prePersist method, I need to ensure that the Game's slug field is unique, which requires a database query. To do the query, I need access to the EntityManager. I can get the EntityManager from inside GameRepository. So: how do I get the GameRespository from a Game?

推荐答案

你不会。 Doctrine 2中的实体应该是不知道实体经理或存储库。

You don't. Entities in Doctrine 2 are supposed to not know of the entity manager or the repository.

对于您出现的情况,典型的解决方案是向用于创建(或调用存储)新实例的存储库(或服务类)添加一种方法,并生成唯一的段值。

A typical solution to the case you present would be to add a method to the repository (or a service class) which is used to create (or called to store) new instances, and also produces a unique slug value.

这篇关于如何从实体获取反应物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆