代码之家  ›  专栏  ›  技术社区  ›  prodigitalson

原则1.2:我如何防止一个反义词被分配到一对多关系的两边?

  •  -1
  • prodigitalson  · 技术社区  · 16 年前

    有没有办法阻止教义在一对一关系的双方都分配一个反例?我尝试将定义从一方移动到另一方,并使用拥有方,但它仍然对两个表都施加了约束。当我只希望父表有一个约束时,即父表可能没有关联的子表。

    例如,我主要使用以下SQL模式:

    CREATE TABLE `parent_table` (
      `child_id` varchar(50) NOT NULL,
      `id` integer UNSIGNED NOT NULL auto_increment,
      PRIMARY KEY (`id`)
    );
    
    CREATE TABLE `child_table` (
      `id` integer UNSIGNED NOT NULL auto_increment,
      `child_id` varchar(50) NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY (`child_id`),
      CONSTRAINT `parent_table_child_id_FK_child_table_child_id`
        FOREIGN KEY (`child_id`)
        REFERENCES `parent_table` (`child_id`)
    );
    

    但是我得到了这样的结果:

    CREATE TABLE `parent_table` (
      `child_id` varchar(50) NOT NULL,
      `id` integer UNSIGNED NOT NULL auto_increment,
      PRIMARY KEY (`id`),
      CONSTRAINT `child_table_child_id_FK_parent_table_child_id`
        FOREIGN KEY (`child_id`)
        REFERENCES `child_table` (`child_id`)
    );
    
    CREATE TABLE `child_table` (
      `id` integer UNSIGNED NOT NULL auto_increment,
      `child_id` varchar(50) NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY (`child_id`),
      CONSTRAINT `parent_table_child_id_FK_child_table_child_id`
        FOREIGN KEY (`child_id`)
        REFERENCES `parent_table` (`child_id`)
    );
    

    我可以手动移除约束或修改访问器来返回/设置集合中的单个实体(使用一对多),但似乎应该有内置的方法来处理这个问题。

    我也在使用symfony 1.4.4(pear installation atm),以防它是一个sfdoctrineplugin问题,不一定是学说本身。

    2 回复  |  直到 12 年前
        1
  •  2
  •   Andrei Dziahel vjache    16 年前

    sfdoctrineplugin以自动创建对边关系的方式配置条令模型生成器。在php 5.2中,您不能用它做任何事情。

    从php 5.3开始,其中 ReflectionProperty::setAccessible() method 可用, you could manipulate protected/private properties 属于 Doctrine_Relation_Parser 实例可以通过 $this->getTable()->getRelationParser() . 所以你必须重写 BaseSomething::setUp() 方法并使用PHP的反射API手动删除不需要的关系。您必须使用反射API,因为 条令关系分析 不提供允许随意删除关系的方法。

        2
  •  1
  •   Besnik hsz    12 年前

    我通过为相反的“空对象”设置条令状态来解决这个问题。 以前 我们保存记录:

    /* @var $address Address */
    $address = $form->getObject();
    
    // the null object is here the "address position", let's change it's state
    $address->getAddressPosition()->state(Doctrine_Record::STATE_CLEAN);
    
    // now we can save the address and doctrine won't insert the null object
    $address = $form->save();