這與其說是一個問題,不如說是一個問題。我有 2 個由多對一關系關聯的物體:
class TestScore {
[...]
/**
* @ORM\ManyToOne(targetEntity="Modules\TestBundle\Entity\TestUser" , cascade={"persist"}, inversedBy="scores")
* @ORM\JoinColumn(name="test_user_id", onDelete="CASCADE")
*/
private $testUser;
[...]
}
class TestUser {
[...]
/**
* @ORM\OneToMany(targetEntity="Modules\TestBundle\Entity\TestScore" , cascade={"persist"}, mappedBy="testUser")
*/
private $scores;
[...]
}
在服務中,我有類似的東西:
public function createScore(TestUser $testUser, string $code, $score, string $description = null) {
$testScore = new TestScore();
$testScore->setTestUser($testUser);
$testScore->setCode($code);
$testScore->setScore($score);
$testScore->setDescription($description);
$this->em->persist($testScore);
}
In this case, if I make something like :
$scoringService->createScore($testUser, 'total', $totalActivity);
dump($em->getRepository(TestScore::class)->findBy('testUser' => $testUser));
dump($testUser->getScores());
我的第一個轉儲回傳 1 TestScore 和正確的資料,我的第二個回傳 null !
但如果我添加
$testUser->addScores($testScore);
到$scoringService->createScore(),我的第二次轉儲回傳正確的資料。
我認為學說會自動為 testUser 添加分數,而 $testScore->setTestUser($testUser);
有人可以向我確認嗎?謝謝 !!
uj5u.com熱心網友回復:
當從資料庫加載這種資料時,Doctrine 會自動從雙方創建/填充連接(即,如果您要在其他時間再次加載用戶,它將鏈接 testScore 實體)。
但是,當您最初創建物體并設定參考時,如果您想立即對同一物件使用參考,則需要在兩側進行設定/添加。一個相當標準的解決方案(例如由 symfony 物體生成器使用)是在 oneToMany side add 方法中設定參考的兩側,例如:
public function addScores(TestScore $testScore): self
{
if (!$this->testScores->contains($testScore)) {
$this->testScores[] = $testScore;
$testScore->setTestUser($this);
}
return $this;
}
并且您只需要從您的服務中呼叫 addScores 并讓物體代碼填充當前實體的連接的另一端。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/317354.html
