Doctrine orm 使用ArrayCollection字段更新条令实体

Doctrine orm 使用ArrayCollection字段更新条令实体,doctrine-orm,symfony,arraycollection,symfony-3.1,Doctrine Orm,Symfony,Arraycollection,Symfony 3.1,我在使用关系(一对多、多对一)更新实体时遇到问题。我试图在更新时向ArrayCollection添加一些新元素,但没有做什么。 以下是我创建和添加关系的代码: $auctionPhoto = new AuctionPhoto(); $auctionPhoto->setAuction($auction); $auctionPhoto->setPath($path); $auction->getPhotos()->add($auctionPhoto); 所有这些都由条令实体

我在使用关系(一对多、多对一)更新实体时遇到问题。我试图在更新时向ArrayCollection添加一些新元素,但没有做什么。 以下是我创建和添加关系的代码:

$auctionPhoto = new AuctionPhoto();
$auctionPhoto->setAuction($auction);
$auctionPhoto->setPath($path);
$auction->getPhotos()->add($auctionPhoto);
所有这些都由条令实体侦听器(preUptade)运行。当我创建实体(prePersist)时也会执行相同的代码,但这样就可以了


我调试了这个,在持久化之前,我有拍卖对象权限关系,但没有保存到数据库。

在运行这个之前,你是说数据库中没有任何内容:

$em->persist($auction);
$em->flush();

如果是这样,这就是正确的功能。您需要先保存,然后刷新,然后存储数据。

为什么要添加($auctionPhoto)

您应该在您的
拍卖
实体中有一个方法
addPhoto()
addAuctionPhoto()
,并像这样使用它:

$auction->addPhoto($auctionPhoto)
$auction->addAuctionPhoto($auctionPhoto)

编辑:


可能您的实体
Auction
不是这两个实体之间关系的所有者,那么您需要添加
$auctionPhoto->setAuction($Auction)
,或者如果是多个关系,那么添加
$auctionPhoto->addAuction($Auction)

替换
$Auction->getPhotos()->add($auctionPhoto)带有
$auction->addPhoto($auctionPhoto)

拍卖
实体中,定义新方法

// Auction.php
public function addPhoto(AuctionPhoto $thePhoto)
{
    $this->photos[] = $thePhoto; // Add the photo to the object
    $thePhoto->setAuction($this); // AuctionPhoto entity need to know about the reference

    return $this; // Just for method chaining
}
(我假设
$photos
是您的ArrayCollection,其中包含拍卖的照片)

基本上,您错过的是给您的实体提供参考:
$thePhoto->setAuction($this)

不,这不是这个。其他拍卖领域,如所有权保存。正如我所说,这和create action中的代码是一样的,但是create可以工作。我没有任何代码。这个方法看起来怎么样?在这个方法中,你应该有
$this->photos->add($auctionPhoto)
。这两种方法的不同之处在于
$auction->getPhotos()
返回一个与照片值相同的数组,而不是照片的引用。下次,使用
php bin/console原则生成实体:generate:entities-AppBundle/Entity/yourtentity
Doc:我不确定。在我尝试创建新的ArrayCollection之前,先向其中添加照片,然后再使用setPhotos on Auction-但不起作用。您可以运行
php bin/console原则:generate:entities-AppBundle/Entity/YourEntity
并查看Symfony将为您创建哪些方法。您的当前实体名为
~YourEntity
,它将为您生成一个新的实体文件。或者,您的实体
Auction
不是这两个实体之间关系的所有者,您需要添加
$auctionPhoto->setAuction($Auction)
,或者如果有很多,请添加
$auctionPhoto->addAuction($Auction)