如何从实体获取 Respository? [英] How to get a Respository from an Entity?
问题描述
我有一个名为 Game
的实体和一个名为 GameRepository
的相关存储库:
I have an Entity called Game
with a related Repository called GameRepository
:
/**
* @ORMEntity(repositoryClass="...GameRepository")
* @ORMHasLifecycleCallbacks()
*/
class Game {
/**
* @ORMprePersist
*/
public function setSlugValue() {
$this->slug = $repo->createUniqueSlugForGame();
}
}
在prePersist方法中,我需要保证Game的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.
针对您提出的案例的典型解决方案是向存储库(或服务类)添加一个方法,该方法用于创建(或调用以存储)新实例,并生成唯一的 slug 值.
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.
这篇关于如何从实体获取 Respository?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!