2012-09-14 22 views
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(); 
} 

什麼是做到這一點的最好方法是什麼?

另外我想知道是否將自定義設置/創建方法放入存儲庫是一種很好的做法?

回答

2

根據定義,您不能從實體對象中調用存儲庫類的方法......這是基本的面向對象編程。

我想你應該建立在Category實體addArticle功能,這樣的事情:

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

如果級聯配置正確,這將工作

+0

那麼,甚至用於存儲設置/添加方法的存儲庫?或者他們僅適用於獲取方法? –

0

您可以編寫自己的存儲庫管理器並根據需要創建方法。

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

+0

這正是我在我的例子中所做的:)問題是更多關於在存儲庫中設置/添加方法。最好的方式來做到這一點。 –

+1

存儲庫中的代碼不應創建新對象,只能操作實體。 您的代碼最好放在控制器中 – Maks3w

+0

謝謝您的回答。這是我想知道的。 –

相關問題