cakephp 3关联模型的树行为

时间:2017-06-03 18:49:43

标签: cakephp tree associations cakephp-3.0

我正在使用cakephp 3.4.2并且正在执行blog tutorial以重新进入新的cakephp。我决定按照教程,但将其打包为插件。

有一个文章模型和一个类别模型,我们在CategoriesTable.php的initialize()方法中使用Tree Behavior。

public function initialize(array $config)
{
    $this->table('categories');
    $this->displayField('name');
    $this->primaryKey('id');

    $this->addBehavior('Tree');

    $this->belongsTo('ParentCategories', [
        'className' => 'Blog.Categories',
        'foreignKey' => 'parent_id'
    ]);
    $this->hasMany('Articles', [
        'foreignKey' => 'category_id',
        'className' => 'Blog.Articles'
    ]);
    $this->hasMany('ChildCategories', [
        'className' => 'Blog.Categories',
        'foreignKey' => 'parent_id'
    ]);
}

当你在CategoriesController.php添加或编辑函数中调用treeList finder方法时,它工作正常,并且线程列表很好地显示在表单的选择列表中。

ArticlesController.php添加和编辑功能

public function add()
{
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {
        $article = $this->Articles->patchEntity($article, $this->request->getData());
        if ($this->Articles->save($article)) {
            $this->Flash->success(__('Your article has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('Unable to add your article.'));
    }
    $this->set('article', $article);

    $categories = $this->Articles->Categories->find('treeList');
    $this->set(compact('categories'));
}

抛出错误:

Unknown finder method "treeList"

我已经尝试在ArticlesTable.php中实例化Tree行为,就像我在CategoriesTable.php中所做的那样(尽管我认为不应该这样做)但是这不起作用 - 并且错误仍然存​​在。 任何建议将不胜感激。

debug($this->Articles->Categories->target());调试

`/plugins/Blog/src/Controller/Admin/ArticlesController.php(第51行) object(Cake \ ORM \ Table){

'registryAlias' => 'Categories',
'table' => 'categories',
'alias' => 'Categories',
'entityClass' => '\Cake\ORM\Entity',
'associations' => [],
'behaviors' => [],
'defaultConnection' => 'default',
'connectionName' => 'default'

}`

ArticlesTable.php初始化函数:

public function initialize(array $config)
{
    $this->table('articles');
    $this->displayField('title');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->belongsTo('Categories', [
        'foreignKey' => 'category_id',
    ]);

}

1 个答案:

答案 0 :(得分:0)

感谢ndm指出这一点......

belongsTo关联应指向Blog.Categories