Propel ORM用于定义父子关系的行为



我将Symfony2与PropelBundle一起使用,假设我有以下模式:

<table name="person">
  <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/>
  <column name="name" type="VARCHAR" size="100" required="true"/>
</table>
<table name="person_parent">
  <column name="person_id" type="INTEGER" primaryKey="true" required="true"/>
  <column name="parent_id" type="INTEGER" primaryKey="true" required="true"/>
</table>

想想看,一个人可以有很多"父母",就像父母可以有很多孩子"人"一样。"person_parent"表中的两列都是"person"表的外键。与像Book/Author这样的关系不同,可以在表"Book_Author"的架构中设置isCrossRef="true",让Propel生成直接从Author类获取/设置/添加图书对象的方法,反之亦然,对于父/子关系,不可能设置isCrossRef="true",因此不可能直接从"Person"对象获取/设置或添加Parent Person对象。换句话说,这是不可能做到的:

$person = new Person();
$person->setPersonParents($personCollection);

用于设置任何给定人员的所有父"Person"对象的方法"setPersonParents()"不可用。但是,对于像author_book这样不引用同一个表的交叉表,设置isCrossRef="true"可以实现以下功能:

$author = new Author();
$author->setBooks($bookCollection);

考虑到这一点,也不可能在"新人"表格中直接选择一个人的"父母"…

对于类似朋友的关系,有EqualNestBehavior,它允许:

$person = new Person();
$person->setFriends($personCollection);

然而,这种行为似乎不适用于父母/子女关系,因为它不在乎等级制度(如果一个人试图获得任何给定"人"的"父母",那么除了"父母"之外,还可以获得该"人"所有的"子女"…)。这是人们在"朋友式"关系中所期望的行为,一个人的朋友也是该人的朋友。

是否有方法将EqualNestBehavior用于父/子案例?或者有没有其他Propel行为或方法来处理这种关系?

我不确定EqualNestBehavior,但您可以按以下方式设置工作流。

在您的模式中,将FKs定义为Person表:

<table name="person">
    <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/>
    <column name="name" type="VARCHAR" size="100" required="true"/>
</table>
<table name="person_parent">
    <column name="person_id" type="INTEGER" primaryKey="true" required="true"/>
    <column name="parent_id" type="INTEGER" primaryKey="true" required="true"/>
    <foreign-key foreignTable="person" name="p1" onDelete="CASCADE" onUpdate="CASCADE">
        <reference local="person_id" foreign="id"/>
    </foreign-key>
    <foreign-key foreignTable="person" name="p2" onDelete="CASCADE" onUpdate="CASCADE">
        <reference local="parent_id" foreign="id"/>
    </foreign-key>
</table>

之后,当你生成模型时,你会得到这样的方法:

$person = new Person();
$person->getPersonParentsRelatedByParentId();
$person->setPersonParentsRelatedByParentId($personCollection);
$person->getPersonParentsRelatedByPersonId();
$person->setPersonParentsRelatedByPersonId($personCollection);

设置程序接受PropelCollection作为参数。

你只需要考虑这种情况,而不是像"得到父母"或"得到孩子"那样,而是相关的因素。

最新更新