Doctrine setter在多对多关系中有什么用?

时间:2011-04-15 15:01:23

标签: php symfony1 doctrine persistence many-to-many

今天我在教义(1.2)上遇到了一些意想不到的行为。

情况

我有一个Document课程和一个Anomaly课程。 Document可以包含多个Anomalies,而Anomaly可以找到Documents

#schema.yml

Document:
  columns:
    id:       { type: integer(12), primary: true, autoincrement: true }
    scan_id:  { type: integer(10), notnull: true }
    name:     { type: string(100), notnull: true }

Anomaly:
  columns:
    id:     { type: integer(5), primary: true, autoincrement: true }
    label:  { type: string(200) }
    value:  { type: integer(6), notnull: true, unique: true }
  relations:
    Documents:
      class:        Document
      refClass:     DocumentAnomaly
      local:        anomaly_id
      foreign:      document_id
      foreignAlias: Anomalies

DocumentAnomaly:
  columns:
    document_id:  { type: integer(12), primary: true }
    anomaly_id:   { type: integer(5), primary: true }
  relations:
    Anomaly:  { local: anomaly_id, foreign: id }
    Document: { local: document_id, foreign: id }

问题

我想实例化一个新的Document,为它赋予一些属性值,并为他分配一个Anomaly列表。

#sample code

$anomalies = Doctrine_Core::getTable('Anomaly')->getSomeAnomalies(); //returns a valid and non empty Doctrine_Collection of Anomalies

$document = new Document();
$document->setName('test')
  ->setScanId(3574)
  ->setAnomalies($anomalies)
  ->save();

echo $document->getId(); // "1"
print_r($document->getDocumentAnomaly()->toArray(); // empty array
print_r($document->getAnomalies()->toArray(); //correct array, listing anomalies from "->getSomeAnomalies()"

后果: Document在数据库中保留,但不是指向其AnomaliesDocumentAnomaly表/对象)的链接。

解决方法

$anomalies = Doctrine_Core::getTable('Anomaly')->getSomeAnomalies();

$document = new Document();
$document->setName('test')
  ->setScanId(3574)
  ->setAnomalies($anomalies)
  ->save();

foreach ($anomalies as $anomaly)
{
  $documentAnomaly = new DocumentAnomaly();
  $documentAnomaly->setDocument($document)
    ->setAnomaly($anomaly);
  $documentAnomaly->save();
}

//Document is persisted, *and it's DocumentAnomalies too*.

我的问题

$document->setAnomalies()方法的用途是什么?有没有 ?我错过了什么吗?

感谢。

1 个答案:

答案 0 :(得分:1)

$文档 - > Anomalies->添加($异常);