Symfony和Doctrine模板 - 建立一对多的关系
在我的数据库模式中,我有几个与父表相关的表。解决关系问题的“丑陋”方法是在模式中手动包含依赖项:
sfArea:
columns:
id: integer
name: string
sfCity:
columns:
name: string
area_id: integer
relations:
Area:
class: sfArea
local: area_id
foreignType: many
foreignAlias: Cities
sfItem:
columns:
name: string
area_id: integer
relations:
Area:
class: sfArea
local: area_id
foreignType: many
foreignAlias: Items
但是,每次我要添加一个要附加到该区域的类时,我都需要添加关系以及随之而来的所有行(copy / paste => future hell)。这是我决定使用Doctrine_Template的地方,它允许我实现同样的事情:
sfArea:
columns:
id: integer
name: string
sfCity:
actAs:
AreaRelated: { foreignAlias: Cities }
columns:
name: string
sfItem:
actAs:
AreaRelated: { foreignAlias: Items }
columns:
name: string
和模板类:
class AreaRelated extends Doctrine_Template
{
protected $_options = array(
'foreignAlias' => ''
);
public function setTableDefinition()
{
$this->hasColumn('area_id', 'integer');
}
public function setUp()
{
$this->hasOne('sfArea as Area', array(
'local' => 'area_id',
'foreign' => 'id',
'foreignType' => 'many',
'foreignAlias' => $this->_options['foreignAlias']
)
);
}
}
表格生成正确,关系在$ sfCity-> Area方向上有效。但是,不应创建应在sfArea类中设置的关系($ sf_area-> Cities在“sfArea”上给出错误“未知记录属性/相关组件”城市“”)。
如何创建其他关系?我甚至尝试过(没有成功):
//...
public function setUp()
{
$thisTable = $this->_table;
$areaTable = Doctrine::getTable("smArea");
$thisTable->hasOne('smArea as Area', array(
'local' => 'area_id',
'foreign' => 'id',
'foreignType' => Doctrine_Relation::MANY
)
);
$areaTable->hasMany($thisTable->getOption('name') . ' as ' . $this->_options['foreignAlias'], array(
'local' => 'id',
'foreign' => 'area_id',
'foreignType' => Doctrine_Relation::ONE
)
);
}
没有找到相关结果
已邀请:
3 个回复
弓萍功
然后在
中附上关系
当然,这种方法是不灵活的,如果你想要更复杂的逻辑或选项,这种方法效果不是很好。您可以始终仅在区域上定义关系,但继续在关系的多个方面使用行为。 与其他一些答案相反,我确实认为这是一种合理的方法,可能是一个好主意。 Symfony / Doctrine哲学的核心原则是不要重复自己。这个解决方案坚持这个想法。如果在AreaRelated的类之间共享逻辑,它还提供了显着的好处。 *除了一个丑陋的:你可以遍历每个表并找到任何具有模板AreaRelated的表。这将需要在每次加载区域记录时实例化每个表,这听起来像一个绝对可怕的想法。
讼乐
惜堡沁戚
使用mode_class_name作为提示知道如何处理原始数据,您可以执行以下操作:
因此,您已将DatabaseHirearchy移至PhpObjectHirearchy 希望这在某种程度上有所帮助,如果您需要更多细节,我很乐意提供帮助!