我想知道我的学说收藏中是否有一件物品


I would like to know if an object is in my Doctrine Collection

我正在使用条令1.2开发Symfony 1.4,我遇到了一些问题。

我为我的产品创建了一个条令系列,如下所示:

$oProductCollection = new Doctrine_Collection('Products');

我在中添加了一些产品

$oProductCollection->add($oMyProduct);

然后我想知道我的收藏中是否已经有产品。因为如果我添加两次我的产品,就会覆盖我的旧版本。。。

我找到了"包含"功能,但我不能直接给我的产品对象,我不知道关键是什么…

你能帮我吗?

您可以通过设置keyColumn

//set the id column as key
$oProductCollection = new Doctrine_Collection('Products', 'id');

然后您可以使用$oProductCollection->contains($oMyProduct->getId());来检查$oMyProduct是否已经在您的集合中。

现在您可以编写了

if ($oProductCollection->contains($oMyProduct)){
   echo "Its already in";
}else{
   $oProductCollection->add($oMyProduct);
}

另一种选择。按id为您的收藏建立索引,然后检查它是否存在。应该很快。看一下文档。

类似于:

$id = $oMyProduct->getId();    
if (!empty($oProductCollection[$id])){
    ...
}

您应该实现一个方法Produit::equals(Produit$p),使用循环检查集合的每个对象。

foreach ($oListeProduit as $p) {
  if ($p->equals($produit)) {
    return true;
  }
}
return false;

您必须使用Doctrine_Collection构造函数的第二个参数:

public function __construct($table, $keyColumn = null)

因此:

$oProductCollection = new Doctrine_Collection('Products', 'id');

然后具有id的contains将工作。

编辑:烧烤:(