DijkeMark
DijkeMark

Reputation: 1306

CakePHP 3 - DB table assocciation with itself

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.

This is how the table looks:

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

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()
);

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.

Any idea on how this is still possible is much appreciated!

Upvotes: 1

Views: 832

Answers (1)

rrd
rrd

Reputation: 1451

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'
]);

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.

Upvotes: 1

Related Questions