簡體   English   中英

教義不會添加持久實體關系

[英]Doctrine won't add persist entity relationship

我有兩個實體, ViewLocation

每個View可以有一個Location

因此,我認為:

class View
{
    //..... Other Stuff.....

    /**
     * @ManyToOne(targetEntity="Location", inversedBy="views")
     **/
    private $location;

    //...setters and getters....

    public function setLocation($location){
        $this->location = $location;
    }

}

然后針對我的位置

class Location
{
    //.....other stuff.....

    /**
     * @OneToMany(targetEntity="View", mappedBy="location")
     **/
    private $views;

    public function __construct() {
        $this->created = $this->updated = new \DateTime("now");
        $this->views = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // .... Getters and Setters ....
}

但是當我嘗試這樣做時:

<?php
    $this->pageview = $this->em->getRepository('Entities\View')->find(1);
    $this->location = $this->em->getRepository('Entities\Location')->find(1);
    $this->pageview->setLocation($this->location);
    $this->em->persist($this->pageview);
    $this->em->flush();
?>

甚至當我創建新實體時:

<?php
    $pv = new Entities\Pageview;
    $lc = new Entities\Location;
    $this->em->persist($lc);
    $this->em->flush();
    $pv->setLocation($lc);
    $this->em->persist($pv);
    $this->em->flush();
?>

原則永遠不會在數據庫中設置location_id(始終為NULL)。

我已經檢查了SQL查詢,甚至沒有嘗試設置它們,我得到的只是:

INSERT INTO View (field1, field2, created, updated) VALUES ('val1', 'val2', '2013-07-17T12:10:56+01:00', '2013-07-17T12:10:56+01:00')

根本沒有引用位置...奇怪的是我可以很好地更新field1和field2 ...並且所有其他關系都在我的整個應用程序中正常工作...我只是無法獲取視圖和位置...

編輯

我現在有確切的代碼可以在另一台計算機上工作。 我不知道為什么它不起作用,但我只是將文件移回並重新啟動計算機,現在是...我猜是緩存問題?

重新啟動計算機,問題解決了...我不知道為什么出問題了!

也許與緩存或代理有關...我不知道...

您可以嘗試顯式引用Doctrine進行連接所需的正確列。

/**
 * @ManyToOne(targetEntity="Location")
 * @JoinColumn(name="location_id", referencedColumnName="id")
 */
private $location;

另外,在此示例中:

$this->pageview = $this->em->getRepository('Entities\View')->find(1);
$this->location = $this->em->getRepository('Entities\Location')->find(1);
$this->pageview->setLocation($this->location);
$this->em->persist($this->pageview);
$this->em->flush();

如果您僅更新現有數據,則無需保留實體。

我認為您需要在該位置加載視圖。 因此,您必須像這樣在Location實體中創建一個方法:

public function getViews() {
    return $this->views;
}

然后堅持到數據庫中,執行以下操作:

$location = new Entity\Location();
$view = new Entity\View();
$location->getViews()->add($view);
$this->em->persist($location)
$view->setLocation($location);
$this->em->persist($view);
$this->em->flush();

這與Doctrine ORM緩存驅動程序有關:

doctrine:
    orm:
        entity_managers:
            default:
                metadata_cache_driver: apcu
                result_cache_driver: apcu
                query_cache_driver: apcu

我們甚至使用APCu甚至在DEV進行緩存,清除APCu(通過重新啟動Apache)也可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM