Doctrine不会添加持久的实体关系

时间:2013-07-17 11:13:26

标签: php doctrine-orm doctrine associations model-associations

我有两个实体,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();
?>

Doctrine 从不在数据库中设置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 ...并且所有其他关系在我的应用程序中都有效...我只是无法获得视图和位置工作..

修改

我现在正在另一台计算机上运行一些代码。我不知道为什么它不起作用,但我只是将文件移回并重新启动我的计算机,现在它是......我想是缓存问题?

4 个答案:

答案 0 :(得分:1)

重新启动我的电脑,问题解决了......我不知道为什么会出错!

也许与缓存或代理有关...我不知道......

答案 1 :(得分:0)

您可以尝试显式引用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();

如果您只是更新现有数据,则无需保留实体。

答案 2 :(得分:0)

我认为您需要在该位置加载视图。因此,您必须在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();

答案 3 :(得分:0)

这与Doctrine ORM缓存驱动程序有关:

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

我们使用APCu甚至在DEV进行缓存,清除APCu(通过重启Apache)就可以了。