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);
精彩评论