是否可以在实体上调用存储库方法? 我的意思是这样的
Is it possible to call repository method on entity? I mean something like this
$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId)); $category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86)); $article->addArticleToCategory($category);其中addArticleToCategory是存储库中的方法(只是示例代码)
Where addArticleToCategory is method in repository (just an example code)
public function addArticleToCategory($category){ $categoryArticles = new CategoryArticles(); $categoryArticles->setArticle(!!/** This is where I want to have my variable $article from this method call **/!!); $categoryArticles->setCategory($category); $this->getEntityManager()->persist($categoryArticles); $this->getEntityManager()->flush(); }最佳方法是什么?
我还想知道将自定义set / create方法放入存储库中是一种好习惯吗?
Also I want to know is it a good practice to put custom set/create methods in repository?
推荐答案根据定义,您不能从实体对象调用存储库类的方法...这是基本的面向对象编程。
By definition you can't call a method of your repository class from an entity object... This is basic object-oriented programming.
我认为您应该在 Category 实体中创建 addArticle 函数,如下所示:
I think you should create addArticle function in the Category entity, something like this:
function addArticle($article) { $this->articles[] = $article; $article->setCategory($this); }然后您做
$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId)); $category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86)); $category->addArticle($article); $em->persist($category); $em->flush();如果级联配置正确,则可以使用
If the cascades are correctly configured, this will work
更多推荐
从实体调用存储库方法
发布评论