【发布时间】: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