【问题标题】:cakephp 3 tree behavior on associated modelcakephp 3 关联模型上的树行为
【发布时间】:2017-06-03 18:49:43
【问题描述】:

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

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

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 行) 对象(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',
    ]);

}

【问题讨论】:

  • 您的帖子缺少触发错误的实际代码...如果没有看到,很难给出任何建议。
  • 我太傻了——对不起。我已经用添加功能编辑了这个问题。道歉。
  • 看起来$this->Articles->Categories 不是您所期望的那样。如果您调试$this->Articles->Categories->target(),您可能会看到它是\Cake\ORM\Table 的实例,而不是具体的ArticlesTable 类? ArticlesTable 类的 initialize() 方法是什么样的?
  • 是的,你是对的。我已经添加了上面的调试代码和 ArticlesTable.php 的初始化方法
  • 那个belongsTo关联应该指向Blog.Categories

标签: cakephp tree associations cakephp-3.0


【解决方案1】:

感谢 ndm 指出这一点...

belongsTo 关联应该指向 Blog.Categories

【讨论】:

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