CakePHP 3-与自己的数据库表关联 [英] CakePHP 3 - DB table assocciation with itself

查看:66
本文介绍了CakePHP 3-与自己的数据库表关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a table in my DB that has a association with itself. I am trying to get all parent categories with their child categories, but I can't get it to work.

这是表格的样子:

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

现在,显然 forum_category_id是引用同一表的父ID。

Now, obviously the "forum_category_id" is the parent id that refers to the same table.

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

I baked the model and this is in the table file:

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

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

The code I use to load from DB is this:

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

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

With this code, I do get the parent categories, but not the children. So I thought to use "Contain", but that only returns empty parent categories.

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

我不知道如何获取子类别。我读过一些有关使用线程化(到目前为止没有结果/成功)或TreeBehaviour的知识,但是我对如何使用它们并不了解。

I have no idea how to get the child categories. I read something about using "Threaded" (no results/success so far) or the TreeBehaviour, but I don't really any idea on how to use them.

任何

推荐答案

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

You should use different aliases for the 2 association.

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

通过此 $ this-> ForumCategories-> find()将给您的父母和 $ this-> ForumChilfCategories-> find()孩子。

By this $this->ForumCategories->find() will give you the parent and $this->ForumChilfCategories->find() the children.

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

Otherwise - if that is option - change your database schema and use tree behaviour.

这篇关于CakePHP 3-与自己的数据库表关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆