2

是否可以在实体上调用存储库方法?我的意思是这样的

$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId));
$category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86));

$article->addArticleToCategory($category);

其中 addArticleToCategory 是存储库中的方法(只是示例代码)

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

最好的方法是什么?

另外我想知道将自定义设置/创建方法放在存储库中是一种好习惯吗?

4

2 回答 2

3

根据定义,您不能从实体对象调用存储库类的方法……这是基本的面向对象编程。

我认为您应该在实体中创建addArticle函数,如下所示:Category

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();

如果级联配置正确,这将起作用

于 2012-09-14T09:55:15.170 回答
0

您可以编写自己的存储库管理器并根据需要创建方法。

http://docs.doctrine-project.org/en/2.0.x/reference/working-with-objects.html#custom-repositories

于 2012-09-14T10:35:37.090 回答