代码之家  ›  专栏  ›  技术社区  ›  takeshin

条令:如何只保存数据库中不存在的收集项

  •  1
  • takeshin  · 技术社区  · 15 年前

    我有一个要保存到数据库的项目集合,但我希望仅在不存在的情况下插入记录。

    我认为最有效的方法是在保存之前过滤集合。条令能自动做到吗?

    或者我应该获取集合中所有项的所有ID,然后查询数据库中这些ID列表中不存在的项,然后在foreach中删除我们不需要的所有集合项,最后保存集合?

    有什么更好的建议吗?

    2 回复  |  直到 13 年前
        1
  •  2
  •   Travis    15 年前

    这是条令收集类的保存功能

     public function save(Doctrine_Connection $conn = null, $processDiff = true)
        {
            if ($conn == null) {
                $conn = $this->_table->getConnection();
            }
    
            try {
                $conn->beginInternalTransaction();
    
                $conn->transaction->addCollection($this);
    
                if ($processDiff) {
                    $this->processDiff();
                }
    
                foreach ($this->getData() as $key => $record) {
                    $record->save($conn);
                }
    
                $conn->commit();
            } catch (Exception $e) {
                $conn->rollback();
                throw $e;
            }
    
            return $this;
        }
    

    我不知道你从哪里得到你的收藏,或者如果你是手动构建它,但是你可能想尝试扩展条令收集类并像这样重载save函数。

    <?php
    
    class My_Collection extends Doctrine Collection
    {
    
      public function save(Doctrine_Connection $conn = null, $processDiff = true, $createOnly = true)
        {
            if ($conn == null) {
                $conn = $this->_table->getConnection();
            }
    
            try {
                $conn->beginInternalTransaction();
    
                $conn->transaction->addCollection($this);
    
                if ($processDiff) {
                    $this->processDiff();
                }
    
                foreach ($this->getData() as $key => $record) {
    
                    if($createOnly)
                    {
                        if ($record->exists())
                        {
                            $record->save($conn);
                        }
                    }else{
                        $record->save($conn);
                    }
                }
    
                $conn->commit();
            } catch (Exception $e) {
                $conn->rollback();
                throw $e;
            }
    
            return $this;
        }
    
    }
    
        2
  •  0
  •   Quasipickle    15 年前

    我对学说一无所知,但MySQL 替换 查询只执行您所需的操作-如果未找到主键匹配项,则更新现有行并创建新行。

    推荐文章