【问题标题】:Save many-to-many in form manually手动在表单中保存多对多
【发布时间】:2011-01-28 20:44:34
【问题描述】:

我有一个模型,有 3 个表,多对一多,如下所示

(缩短的 schema.yml)

PeerEngagement:
  columns:
    id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }
    peer_id: { type: integer(4), notnull: true }

 relations:
   Peer: { local: peer_id, class: Person }

Person:
  columns:
    id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }
    nhi: { type: string(7) }
    name: { type: string(100), notnull: true }

  relations:
    Ethnicity: { class: Ethnicity, refClass: PersonEthnicity, local: person_id, foreign: ethnicity_id  }

PersonEthnicity:
  columns:
    id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }
    person_id: { type: integer(4), notnull: true }
    ethnicity_id: { type: integer(4), notnull: true }
  relations:
    Person:
      class: Person
      local: person_id
      onDelete: CASCADE
    Ethnicity:
      class: Ethnicity
      local: ethnicity_id
      onDelete: RESTRICT


Ethnicity:
  columns:
    id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }
    name: { type: string(50) }

将这些内容保存在自动生成的表单中很好。但是在特殊情况下,我需要在 PeerEngagementForm 中分别保存 nhi 和种族。

为了保存 nhi 我有工作:

function doSave($con=null){

  ...

  if(isset($this->values['nhi'])){
    $this->getObject()->getPeer()->setNhi($this->values['nhi']);
    $this->getObject()->getPeer()->save();
  }

  ...

但同样的技术不适用于

if(isset($this->values['ethnicity_list'])){

   $this->getObject()->getPeer()->setEthnicity($this->values['ethnicity_list']);
   $this->getObject()->getPeer()->save();
}

我得到的错误信息是它需要一个 Doctrine_Collection。

如何正确创建此集合,或者如何从顶部表单或操作中保存多对多关系?

【问题讨论】:

    标签: forms symfony1 doctrine save


    【解决方案1】:

    您是否尝试将 $this->values['ethnicity_list'] 放入 Collection 中?

    if(isset($this->values['ethnicity_list'])){
    
    
    $ethnicityLists = new Doctrine_Collection('Ethnicity');
    foreach($this->values['ethnicity_list'] as $ethnicityList){
      $ethnicityLists->add($ethnicityList);
    }
    $peer = $this->getObject()->getPeer();
    $peer->setEthnicity($ethnicityLists);
    $peer->save();
    
    }
    

    应该可以,我按照自己的想法做。

    【讨论】:

      猜你喜欢
      • 2012-06-13
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多