今天我在使用doctrine(1.2)时遇到了一些意想不到的问题。
情况说明:
我有一个Document类和一个Anomaly类。一个Document可以有多个Anomalies,而一个Anomaly可以被多个Documents找到。
情况说明:
我有一个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()"
影响:文档已经被保存到数据库中,但是与其Anomalies
(DocumentAnomaly
表/对象)的链接没有被保存。
解决方法
$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()
方法有什么用?是否有用途?我有遗漏吗?
谢谢。
->getSomeAnomalies()
返回的值的类型(我认为你不能直接传递一个Doctrine_Collection
,而是应该传递记录的数组或类似的东西)。 - NiKoDoctrine_Record
数组时,会抛出异常,因为期望的是一个Doctrine_collection
。 @edem:感谢您提供的链接,我在其中找到了更好的解决方法,但是setAnomalies()
方法的目的是什么? - Clement HerremansetAnomalie
而不是setAnomalies
? - greg0ire