如何清除Doctrine中的集合?

时间:2016-07-01 14:55:24

标签: doctrine-orm

我有这两个学说实体类;

/** @ORM\Entity
  * @ORM\Table(name="computer")
  */
class Computer extends Hardware
{   
    /**
     * @ORM\OneToMany(targetEntity="LogicalDisk", mappedBy="computer", cascade={"persist", "remove"})
     */
    protected $logicalDisks;

    public function __construct()
    {
        $this->logicalDisks = new ArrayCollection();
    }

    public function addLogicalDisk($logicalDisk)
    {
        $this->logicalDisks[] = $logicalDisk;
        $logicalDisk->setComputer($this);
    }

    public function clearLogicalDisks()
    {
        $this->logicalDisks->clear();
    }
}


/** @ORM\Entity
  * @ORM\Table(name="logical_disk")
  */
class LogicalDisk
{
    /**
     * @ORM\ManyToOne(targetEntity="Computer", inversedBy="logicalDisks")
     * @ORM\JoinColumn(name="computer_id", referencedColumnName="id")
     */
    protected $computer;
}

我试图清除现有的集合,然后建立一个新的集合。但是旧的实体永远不会从数据库中删除。

    $disks = $WbemServices->ExecQuery("Select * from Win32_LogicalDisk");


    // Delete existing disk info for this host.
    $computer = $service->findByDNSName($host, $domain);
    $computer->clearLogicalDisks();


    // loop through scanned disks and persist each one
    foreach ($disks as $disk) {
        $logicalDisk = new LogicalDisk();
        $logicalDisk->setDeviceId($disk->DeviceId)
                    ->setDescription($disk->Description)
                    ->setFileSystem($disk->FileSystem)
                    ->setCapacity($disk->Size)
                    ->setFreeSpace($disk->FreeSpace);
        $computer->addLogicalDisk($logicalDisk);
    }

    $service->persist($computer);

我已尝试在计算机实体的logicalDisk属性上设置cascade = {" persist"," remove"},但这不会删除这些项目。我还尝试在清除ArrayCollection后保留计算机,但磁盘实体仍未从数据库中删除。

我只需要知道如何清除ArrayCollection,然后将更改持久保存到数据库中,从而删除不需要的实体。

0 个答案:

没有答案