【问题标题】:How to define a unique alias for a self joining association?如何为自加入关联定义唯一别名?
【发布时间】:2015-12-11 11:11:18
【问题描述】:

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

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

SQLSTATE[42000]:语法错误或访问冲突:1066 Not unique table/alias: '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

我该如何解决这个问题?

class CompetitionRegionsTable::initialize 包含这个:

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

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

【问题讨论】:

    标签: cakephp foreign-keys alias self-join cakephp-3.x


    【解决方案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 键,可以将同一个表用作同一个表的不同关联。您甚至可以创建自关联表来创建父子关系 [...]

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多