CakePHP访问hasMany中的表

时间:2013-09-19 14:52:58

标签: php cakephp associations

我遇到了基于this问题的问题。

相同数据库:项目有很多关键字 - 关键字属于项目
要访问Project Table中的Keywords/index.ctp,请轻松使用$keyword['Project']['id'];

但相反,它似乎有点困难。这里有一点代码:

public function view($id = null) 
{
    if (!$id) 
    {
        throw new NotFoundException(__('Invalid project'));
    }
    $this->paginate['Project']['conditions'] = array('Project.id' => $id);
    $this->set('projects', $this->paginate());

    $this->set('project', $project);
}

Projects/view我尝试访问关键字表格:$project['Keyword']['id']我可能期望这不起作用。

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

public function view($id = null) 
{
    if (!$id) 
    {
        throw new NotFoundException(__('Invalid project'));
    }
    $this->Project->bindModel(array('hasMany' => array('Keyword' => array('className' => 'Keyword',
                                                       'foreignKey' => 'project_id')
                                    )), false);
    $this->paginate['conditions'] = array('Project.id' => $id);
    $this->paginate['recursive'] = '2';
    $this->set('projects', $this->paginate('Project'));

    $this->set('project', $project);
}