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

3
今天我在使用doctrine(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()"

影响:文档已经被保存到数据库中,但是与其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()方法有什么用?是否有用途?我有遗漏吗?

谢谢。


也许您正在传递错误的参数。请查看此链接:http://www.doctrine-project.org/projects/orm/1.2/docs/manual/working-with-models%3Amany-to-many-relations/en - Adam Arold
+1,你应该检查 ->getSomeAnomalies() 返回的值的类型(我认为你不能直接传递一个 Doctrine_Collection,而是应该传递记录的数组或类似的东西)。 - NiKo
@NiKo:当尝试传递一个Doctrine_Record数组时,会抛出异常,因为期望的是一个Doctrine_collection。 @edem:感谢您提供的链接,我在其中找到了更好的解决方法,但是setAnomalies()方法的目的是什么? - Clement Herreman
你的代码中为什么写成了 setAnomalie 而不是 setAnomalies - greg0ire
@greg0ire:在提问时打错了一个字,我已经编辑过了,谢谢。 - Clement Herreman
1个回答

1

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

$Document->异常->添加($异常);


谢谢,事实上我不知道你可以使用那种语法来添加/删除。但是,setAnomalies() 的用途是什么? - Clement Herreman
我接受这个答案,因为我从中学到了东西,即使它并没有真正回答我的问题。 - Clement Herreman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接