【问题标题】:I would like to know if an object is in my Doctrine Collection我想知道一个对象是否在我的教义集合中
【发布时间】:2012-01-17 09:22:40
【问题描述】:

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

我已经为我的产品创建了一个 Doctrine 集合,如下所示:

$oProductCollection = new Doctrine_Collection('Products');

我添加了一些产品:

$oProductCollection->add($oMyProduct);

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

我找到了“contains”函数,但我不能直接给出我的产品对象,也不知道关键是什么......

你能帮帮我吗?

【问题讨论】:

    标签: php symfony1 doctrine


    【解决方案1】:

    现在你可以写了

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

    【讨论】:

      【解决方案2】:

      您可以通过

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

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

      【讨论】:

        【解决方案3】:

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

        类似:

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

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

          • 效率不高,xdazz的方法更好。
          【解决方案5】:

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

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

          所以:

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

          然后带有 id 的 contains 将起作用。

          编辑:烤:(

          【讨论】:

          • 这个解决方案是我的。谢谢
          猜你喜欢
          • 2017-07-17
          • 2010-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多