2013-03-04 112 views
2

我得到以下致命錯誤而調用entityRepository的查找方法在自定義entityRepository類doctrine2:選擇錯誤

致命錯誤:未捕獲的異常「學說\ ORM \ OptimisticLockException」與消息「無法得到關於非版本控制的實體樂觀鎖Entities \ Comment'在C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ OptimisticLockException.php中:62堆棧跟蹤:#0 C:\ Users \ user \ Desktop \ projects \ interview \ application \ libraries \ Doctrine \ ORM \ EntityRepository.php(140):Doctrine \ ORM \ OptimisticLockException :: notVersioned('Entities \ Commen ...')#1 C:\ Users \ user \ Desktop \ projects \ interview \ application \ models \ Repositories \ CommentRepository.php(24):Doctrine \ ORM \ EntityRepository-> find('Entities \ Commen ...',1)#2 C:\ Users \ user \ Desktop \ projects \面試\應用程序\控制器\ CommentController.php(65):存儲庫\ CommentRepository-> activateByIds(數組)#3 [內部函數]:CommentController-> approveComments()#4 C:\ Users \ user \ Desktop \ projects \ system \ core \ CodeIgniter.php(359):call_user_func_array(Array,Array)#5 C:\ Users \ user \ Desktop \ projects \ interview \ index.php(203):require_once('C:\ Users \ user \ D ...')在C:\用戶\用戶\桌面\項目\訪談\程序\庫\原則\ ORM \ OptimisticLockException.php上線62

這裏有方法,我稱之爲找到

public function activateByIds($arrayOfIds){ 
     if (count($arrayOfIds)>=1) { 
      for ($i=0; $i<count($arrayOfIds); $i++){ 
       $comment = parent::find('Entities\Comment', $arrayOfIds[$i]); 
       $comment->setIsactive(1); 
       $this->_em->merge($comment); 
       $this->_em->flush(); 
      } 
      return true; 
     } 
     else return false; 
    } 

我在做什麼錯?

+0

我在學說和編程本身上都很新穎。無法找出什麼意思,該實體未版本化 – 2013-03-04 11:46:26

回答

0

從我讀你有一個OptimisticLockException

正如this documentation說:

An OptimisticLockException is thrown when a version check on an object that uses optimistic locking through a version field fails.

你可以找到更多關於樂觀鎖here

我的猜測是,他們是有衝突$ comment變量:

  1. 第一次初始化$ comment($ i = 0)註釋#1被加載
  2. 第二次(i = 1,你找到註釋#2但註釋已經是實體並且被管理)$ comment = .. 。試圖給註釋#1註釋#2的值,甚至是uniq的id,所以你正在創建一個衝突。

試試這個:你確信你是不是想重新使用以前的評論,而不是一個新的

public function activateByIds($arrayOfIds){ 
     $comments =array(); 

     if (count($arrayOfIds)>=1) { 
      foreach($arrayOfIds as $i=>$id){ 

       $comments [$i] = $this->getEntityManager()->find('Entities\Comment', $id); //new comment, not the old one! 
       $comments [$i]->setIsactive(1); 
       $this->_em->merge($comments[$i]); 
       $this->_em->flush(); 

      } 
      return true; 
     } 
     else return false; 
     unset ($comments); 
    } 

這樣。

+0

我試過你的建議,但無論如何,我得到這個例外。當我使用parent :: findby代替查找時,我沒有異常。但是當你需要通過id查找時,它不是正確的編碼方式,因爲find的執行時間更短,如果ID是主鍵,則通過id查找 – 2013-03-05 05:24:52

+0

true,請嘗試:$ this-> getEntityManager() - > find(。 ...而不是父:: find(.. – bleuscyther 2013-03-05 05:36:47

+0

太棒了!那有效!!謝謝,男士。但是這種行爲的原因是什麼? – 2013-03-05 06:05:44