2013-06-21 57 views
0

我有兩個表,如哪個是維護兩個表值的最佳方法?

User 
ID name count 
1 cat 2 
2 dog 1 
3 rabbit 1 
4 tiger 0 


Lesson 
ID time student 
1 09:00 1(cat) 
2 10:00 1(cat) 
3 13:00 2(dog) 
4 15:00 3(rabbit) 

User.count意味着每個用戶有多少次出現在課程表中。 我想保持這個號碼正確。

方法A)

您可以通過PHP在每次添加行 課時間遞增User.count但你必須寫兩線當您從

課行添加到課程或刪除行

方法B)

使用PrePersist或更新前(我用的學說2) 但有可能訪問用戶表課實體的更新前被觸發時?

方法C)

你可以連接一些mysql本地方法嗎?

哪種方法是保持這些值的最佳方式?

回答

1
  • 您無法訪問prePersist/postPersist等函數中的其他表/實體。
  • 您不應該使用本機數據庫訪問功能。

您應該創建一個更加面向服務的應用程序。我假設你做你的控制器下面添加一個新的教訓:

$doctrine->getManager->persist($newLesson); 

而是這樣做的,你應該創建一個服務,將做插入和計數您的更新。像LessonService有如下方法:

public function addLesson($lessonModel) { 
    // Add the lesson to the database 

    // Increment the counter here 

} 
+0

謝謝,我會這樣做。 – whitebear

相關問題