开发者

What is the use of Doctrine setter on many-to-many relations?

开发者 https://www.devze.com 2023-02-24 22:23 出处:网络
Today I met some unexpected behavior on doctrine (1.2). Situation I\'ve a Document class, and an Anomaly class. A Document can have many Anomalies, and an Anomaly can be found on many Documents.

Today I met some unexpected behavior on doctrine (1.2).

Situation

I've a Document class, and an Anomaly class. A Document can have many Anomalies, and an Anomaly can be found on many 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 }

Problem

I want to instantiate a new Document, assign it's attributes some value, and assign him a list of 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()"

Consequences: the Document is persisted in the database, but not the link to its Anomalies (DocumentAnomaly table/objects).

Workaround

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

$document = new Document();
$document->setName('test')
  ->setScanId(3574)
  ->setAnomalies($anom开发者_如何学Pythonalies)
  ->save();

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

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

My question

What is the use of the $document->setAnomalies() method ? Is there any ? Am I missing something ?

Thanks.


$Document->Anomalies->add($Anomaly);

0

精彩评论

暂无评论...
验证码 换一张
取 消