Call repository method from entity

2019-07-19 12:26发布

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

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

What is the best way to do it?

Also I want to know is it a good practice to put custom set/create methods in repository?

2条回答
叼着烟拽天下
2楼-- · 2019-07-19 12:46

By definition you can't call a method of your repository class from an entity object... This is basic object-oriented programming.

I think you should create addArticle function in the Category entity, something like this:

function addArticle($article)
{
   $this->articles[] = $article;
   $article->setCategory($this);
}

And then you do

$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

查看更多
成全新的幸福
3楼-- · 2019-07-19 12:46

You can write your own repository manager and create a method for your needs.

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

查看更多
登录 后发表回答