手动保存表单中的多对多

时间:2011-01-28 20:44:34

标签: forms symfony1 doctrine save

我有一个包含3个表的模型,多个到1到多个,如下所示

(缩短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。

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

1 个答案:

答案 0 :(得分:1)

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

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();

}

应该有效,我的做法和我想的一样。