【问题标题】:one form - add to two tables一种形式 - 添加到两个表格
【发布时间】:2011-06-13 10:25:48
【问题描述】:

我如何在 Symfony 1.4 和 Doctrine 中制作一个表格,将数据添加到两个表中? 默认 Symfony 为一个表和模块生成表单。在什么时候我可以编辑它并添加自己的字段? http://www.symfony-project.org/jobeet/1_4/Doctrine/en/03 生成。 例如,我想添加具有新类别的字段。

# config/doctrine/schema.yml
JobeetCategory:
  actAs: { Timestampable: ~ }
  columns:
    name: { type: string(255), notnull: true, unique: true }

JobeetJob:
  actAs: { Timestampable: ~ }
  columns:
    category_id:  { type: integer, notnull: true }
     (...)
    expires_at:   { type: timestamp, notnull: true }
  relations:
    JobeetCategory: { onDelete: CASCADE, local: category_id, foreign: id, foreignAlias: JobeetJobs } 

此表单仅添加 id JobeetJob。我怎样才能添加到 JobeetCategory 中?

【问题讨论】:

    标签: php symfony1 doctrine symfony-1.4 doctrine-1.2


    【解决方案1】:

    您可以在 JobeetJob 表单中嵌入 JobeetCategory 关系。这将使您能够创建工作和类别。查找 sfForm 类的 `embedRelation()̀ 方法。

    【讨论】:

      【解决方案2】:

      您应该在模型中覆盖 save 方法(让我们在 JobeetJob 模型中说)。并将两个模型保存在事务中。下面我保存到产品和复合产品表。但不要忘记 save 方法应该有 2 个功能:insertupdate

      public function save(Doctrine_Connection $conn = null){
        try {
            $conn->beginTransaction();
      
            $isNew = $this->isNew();         
            parent::save($conn); #Save Product
      
            $modelName = $this->moduleArray[$moduleName];
      
            $productId = $this->getId();
      
            if($isNew){ #CREATE new Composite Product and set Product ID and Module Name to it.
      
                $cp = new CompositeProduct();
                $cp->setRelatedModelID($productId);
                $cp->setRelatedModelName($modelName);
                $cp->setTitle($this->getTitle());
                $cp->save();
      
            }else{# UPDATE the Composite Product
      
                $query = Doctrine_Core::getTable('CompositeProduct')
                                      ->createQuery('cp')
                                      ->where('cp.relatedmodelname = ?',  $modelName)
                                      ->andWhere('cp.relatedmodelid = ?', $productId);
                $cp = $query->fetchOne();
      
                $cp->setTitle($this->getTitle());
                $cp->save();
            }
      
            $conn->commit();
        }catch(Doctrine_Exception $e){
            $conn->rollback();
        }
      

      }

      【讨论】:

        猜你喜欢
        • 2017-07-14
        • 2023-02-09
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多