Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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($anomalies)
  ->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.

like image 590
Clement Herreman Avatar asked Feb 02 '26 21:02

Clement Herreman


1 Answers

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

like image 106
jeremyFreeAgent Avatar answered Feb 05 '26 12:02

jeremyFreeAgent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!