在Doctrine 2中使用相关实体ID删除关联

时间:2012-06-12 13:46:11

标签: php symfony doctrine doctrine-orm

Doctrine 2文档声明:

  

删除两个实体之间的关联是类似的   直截了当。有两种策略,按键和按键   元件。

“按键”是什么意思?它是相关实体的id字段,还是集合中相关实体的位置?例如,此处使用$ithComment(即评论的位置):

// Remove by Key
$user->getComments()->remove($ithComment);
$comment->setAuthor(null);

3 个答案:

答案 0 :(得分:1)

它是集合中相关实体的位置。在检查ArrayCollection ..

public function add($value)
{
    $this->_elements[] = $value;
    return true;
}

public function remove($key)
{
    if (isset($this->_elements[$key])) {
        $removed = $this->_elements[$key];
        unset($this->_elements[$key]);

        return $removed;
    }

    return null;
}

您可以看到没有使用对集合项标识符的引用。

答案 1 :(得分:0)

根据Doctrine2 API,一个Doctrine Collection的删除方法,

  

“从集合中删除指定索引处的元素”

(见https://github.com/doctrine/common/blob/master/lib/Doctrine/Common/Collections/Collection.php#L78

我的结论是,你所谈论的关键确实是相关实体的立场。

答案 2 :(得分:0)

我有解决方案,也许对你有好处:

public function addSectors(ArrayCollection $sectors)
{
    foreach($sectors as $k => $sector) {
        $this->addSector($sector);
    }
}    

public function removeSectors($sectors)
{   
    foreach($sectors as $k => $sector) {
        unset($this->sectors[$k]);
    }
}
相关问题