【问题标题】:CakePHP 3 - DB table assocciation with itselfCakePHP 3 - 与自身关联的数据库表
【发布时间】:2015-07-09 14:01:52
【问题描述】:

我的数据库中有一个与自身关联的表。我正在尝试获取所有父类别及其子类别,但无法正常工作。

这是表格的外观:

id | name | description | image | is_child | forum_category_id | level

现在,显然“forum_category_id”是指同一个表的父 id。

我烘焙了模型,这是在表格文件中:

$this->belongsTo('ForumCategories', [
    'foreignKey' => 'forum_category_id'
]);
$this->hasMany('ForumCategories', [
    'foreignKey' => 'forum_category_id'
]);

我用来从数据库加载的代码是这样的:

debug($results = $this->find()
    ->order(['id' => 'ASC'])
    ->where(['is_child' => 0])
    ->toArray()
);

使用此代码,我确实获得了父类别,但没有获得子类别。 所以我想使用“包含”,但这只会返回空的父类别。

debug($results = $this->find()
    ->order(['id' => 'ASC'])
    ->where(['is_child' => 0])
    ->contain([
        'ForumCategories' => function ($q)
        {
            return $q
                ->where(['is_child' => 1]);
        }
    ])
    ->toArray()
);

我不知道如何获取子类别。我读过一些关于使用“Threaded”(到目前为止没有结果/成功)或 TreeBehaviour 的内容,但我真的不知道如何使用它们。

非常感谢任何关于如何实现这一点的想法!

【问题讨论】:

    标签: php mysql cakephp-3.0 model-associations


    【解决方案1】:

    您应该为 2 关联使用不同的别名。

    $this->belongsTo('ForumCategories', [
        'foreignKey' => 'forum_category_id'
    ]);
    $this->hasMany('ForumChildCategories', [
        'className' => 'ForumCategories',
        'foreignKey' => 'forum_category_id'
    ]);
    

    通过这个$this->ForumCategories->find() 会给你父母和$this->ForumChilfCategories->find() 孩子。

    否则 - 如果可以选择 - 更改您的数据库架构并使用树行为。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多