我的目标是向其显示1个项目和许多关键字。我的数据库很简单:
项目有很多关键字
关键字属于项目
到目前为止一切顺利。现在我尝试在ProjectsController
:
public function view($id = null)
{
$this->Project->bindModel(array('hasMany' => array('Keyword' => array('className' => 'Keyword',
'foreignKey' => 'project_id')
)), false);
$this->paginate['Project']['conditions'] = array('Project.id' => $id);
$this->paginate['recursive'] = '2';
$this->set('projects', $this->paginate('Project'));
$Projects = $this->paginate('Project');
$this->set('projects', $this->paginate());
}
通过打印出阵列看起来有些出乎意料:
Array
(
[0] => Array
(
[Project] => Array
(
[id] => 3
[title] => Foo
[created] => 2013-08-05 17:39:07
[modified] => 2013-08-05 17:39:07
)
[Keyword] => Array
(
[0] => Array
(
[id] => 1
[project_id] => 3
[title] => Num1
[demand] => 50000000000
[competition] => 37889.56700
[cpc] => 676.50
[created] => 2013-06-26 17:54:48
[modified] => 2013-09-19 13:37:25
)
)
)
[1] => Array
(
[Project] => Array
(
[id] => 4
[title] => Bar
[created] => 2013-08-05 17:39:07
[modified] => 2013-08-05 17:39:07
)
[Keyword] => Array
(
[0] => Array
(
[id] => 3
[project_id] => 4
[title] => Num1
[demand] => 76534000000
[competition] => 5555.55560
[cpc] => 99.34
[created] => 2013-06-26 17:54:48
[modified] => 2013-09-19 13:37:36
)
)
)
)
现在我遇到了问题,如何用正确的Project.id
显示它?因为新创建的数组包含的代码不同于Project.id
。我的问题是如何过滤右Project.id
以仅在我的/View/[id]
修改
我认为最好的处理方式是这样的数组结构:
Array
(
[Project] => Array
(
[id] => 3
[title] => Lerncoachies
[created] => 0000-00-00 00:00:00
[modified] => 2013-08-05 17:39:07
)
[Keyword] => Array
(
[0] => Array
(
[id] => 1
[project_id] => 3
[title] => Num1
[demand] => 50000000000
[competition] => 37889.56700
[cpc] => 676.50
[created] => 2013-06-26 17:54:48
[modified] => 2013-09-19 13:37:25
)
)
)
)
答案 0 :(得分:1)
public function view($id = null) {
$this->Project->bindModel(array(
'hasMany' => array('Keyword' => array(
'className' => 'Keyword',
'foreignKey' => 'project_id')
)), false
);
$this->Project->recursive = 2;
$project = $this->Project->findById($id);
}
现在你的项目数组应该满足你的要求。
答案 1 :(得分:1)
从描述中看起来您想要为关键字而不是项目分页 - 所以您有“意外结果”。
这是分页项目的预期结果。
如果您想分页关键字,那么:
$this->Project->recursive = 1;
$project = $this->Project->findById($id);
$this->loadModel('Keywords'); // I don't remember if this is needed
$this->paginate['Keywords'] = array(
'project_id' => $project['Project']['id']
);
$this->set('keywords', $this->paginate('Keyword'));
$this->set('project', $project);
您将拥有1个项目的视图,并且您将能够通过排序对与给定项目相关的关键字进行分页。