【问题标题】:What is the use of Doctrine setter on many-to-many relations?Doctrine setter 在多对多关系上有什么用?
【发布时间】:2011-04-15 15:01:22
【问题描述】:

今天我在教义(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()"

后果:Document 被持久化在数据库中,但不是指向其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() 方法有什么用?有没有 ?我错过了什么吗?

谢谢。

【问题讨论】:

  • 也许你传递了错误的参数。看看这个:doctrine-project.org/projects/orm/1.2/docs/manual/…
  • +1,你应该检查->getSomeAnomalies()返回的值的类型(我认为你不能直接传递Doctrine_Collection,而是一个记录数组或类似的东西)。
  • @NiKo: 尝试传递 Doctrine_Record 的数组时抛出异常,因为预期为 Doctrine_collection。 @edem:感谢您的链接,我在其中找到了更好的解决方法,但是,setAnomalies() 方法的目的是什么?
  • 你的代码中为什么写setAnomalie 没有's'?
  • @greg0ire:写这个问题的时候打错了。我编辑了它,ty。

标签: php symfony1 doctrine persistence many-to-many


【解决方案1】:

$Document->异常->add($Anomaly);

【讨论】:

  • 谢谢,事实上我不知道您可以使用该语法添加/删除。但是,setAnomalies() 有什么用?
  • 我接受这个答案是因为我从中学到了一些东西,即使它并没有真正回答这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
相关资源
最近更新 更多