0

我是一个 cakephp 新手。我设计了一个 mysql 数据库,其中包含一个 InnoDB 表 CompetitionRegions 和一个引用该表本身的外键。外键约束已到位。

cake bake 无法为此自动生成正确的代码,因为自联接表别名与第一个别名相同:

SQLSTATE [42000]:语法错误或访问冲突:1066 不是唯一的表/别名:'CompetitionRegions'

SELECT CompetitionRegions.id AS `CompetitionRegions__id`, CompetitionRegions.name AS `CompetitionRegions__name`, CompetitionRegions.parent_competition_region_id AS `CompetitionRegions__parent_competition_region_id` FROM competition_regions CompetitionRegions LEFT JOIN competition_regions CompetitionRegions ON CompetitionRegions.id = (CompetitionRegions.parent_competition_region_id) LIMIT 20 OFFSET 0

我该如何解决这个问题?

CompetitionRegionsTable::initialize 类包含以下内容:

$this->belongsTo('CompetitionRegions', [
        'foreignKey' => 'parent_competition_region_id'
    ]);

有没有办法可以指定用于自联接子查询的别名?

4

2 回答 2

1

第一个参数用作别名,因此您必须更改它。为了让 CakePHP 仍然使用CompetitionRegionsTable该类,您需要通过className选项指定它。

$this->belongsTo('ParentCompetitionRegions', [
    'className' => 'CompetitionRegions',
    // the foreign key options isn't actually necessary with a matching alias
    'foreignKey' => 'parent_competition_region_id'
]);

另请参阅Cookbook > Database Access & ORM > Associations > Linking Tables together

[...] 如您所见,通过指定className键,可以将同一个表用作同一个表的不同关联。您甚至可以创建自关联表来创建父子关系 [...]

于 2015-12-11T15:41:42.137 回答
0

我无法让它与 ndm 单独提出的解决方案一起使用。它给出了另一个问题(ParentCompetitionRegions 关联不存在),我可能无法解决这个问题,因为我对 CakePHP 几乎没有经验。

经过更多研究,我所要做的就是将外键从 parent_competition_region_id 重命名为 parent_id。显然,在这种情况下,cake bake 认为它是一个自引用字段。

于 2015-12-13T11:57:26.027 回答