我想了解爲什麼我無法訪問實體中的id字段,當它是關聯ID的引用時。我已經讀過這種情況,但是我想知道爲什麼給出一個實際的getter,它應該將數據庫中的數據提取出來。無法直接訪問已保存的關聯實體的ID而沒有獲取整個實體
特別是這是一個問題,因爲我需要根據這個id來查詢我的實體,例如,
$article = $articleRepo->findOneByViewVersionId($view->getVersion()->getId());
我有一個Article
實體,它指向了一個單向OneToOne協會一個ViewVersion
實體(因爲viewVersion可以指向很多不同的內容類型,我不能硬編碼這是雙向的。 ..我不知道這是如何another question I've posed)。這會持續到數據庫並在數據庫中設置一個viewVersionId
(我在那裏看到它)。當我從數據庫中獲取實體時,我可以轉儲實體並查看所有字段,但viewVersionId
報告爲NULL,即使它在數據庫中的值爲29!
class Article {
/**
* @ORM\OneToOne(targetEntity="\Gutensite\CmsBundle\Entity\View\ViewVersion")
* @ORM\JoinColumn(name="viewVersionId", referencedColumnName="id")
*/
protected $viewVersion;
protected $viewVersionId;
public function getViewVersion() {
return $this->viewVersion;
}
public function getViewVersionId() {
return $this->viewVersionId;
}
}
如果我取的實體,並嘗試直接打印出viewVersionId,它爲空:
// hard coded fetch for id 14 since $articleRepo->findOneByViewVersionId(29) doesn't work
$content = $articleRepo->find(14);
print('<h1>View version ID: '.$content->getViewVersionId().' (= NULL) </h1>');
print('<h1>View version ID: '.$content->getViewVersion()->getId().'(= 29) </h1>');
\Doctrine\Common\Util\Debug::dump($content, 1);
// this prints out all the fields but the viewVersionId is NULL
object(stdClass)#5095 (14) {
["__CLASS__"]=> string(38) "Gutensite\ArticleBundle\Entity\Article"
["content"]=> string(10) "Article 14"
["profileId"]=> NULL
["id"]=> int(14)
["lockVersion"]=> int(1)
["siteId"]=> NULL
["time"]=> int(1399935757)
["timeMod"]=> NULL
["timeDelete"]=> NULL
["flagDelete"]=> bool(false)
["userId"]=> NULL
["userIdMod"]=> NULL
["viewVersion"]=> string(43) "Gutensite\CmsBundle\Entity\View\ViewVersion"
["viewVersionId"]=> NULL
}
那麼,爲什麼我不能直接訪問的viewVersionId值,如果數據被保存到我的數據庫?我認爲這是因爲OneToOne關聯,但在這種情況下,數據在我的實體中,而且我有一個getter,所以爲什麼它不起作用?
你能嘗試設置變量'private',而不是'protected'?還有什麼'$ contentRepo'設置爲? – phoops
將變量改爲私有沒有什麼區別;(僅供參考,這實際上是在文章實體用'use'聲明調用的特性中定義的,但這根本不重要,我設置了其他變量在這個特性中,例如protected $ foo = 1;並且爲它取得了getters,並且它們取得很好。 –
$ contentRepo(或者我剛剛在我的問題中更新到$ articleRepo)只是entityManager存儲庫:'$ articleRepo = $ em-> getRepository(「GutensiteCmsBundle:Article」);'它可以很好地執行$ articleRepo-> find(14),但不能完成 - > findOneByViewVersionId(29)。 –