我是 cakephp 的新手,并且一直在阅读 Apress 的书“从新手到专业的 CakePHP 入门”,但是在烘焙章节之后遇到了问题。
(如果你看过我最近的另一个问题,你就会知道我不得不跳过那一章,因为我无法让烘焙控制台在我的 win7 机器上工作)。
问题是我认为表关联不再正常工作了,尽管当我在本书开头开始博客应用程序示例时它们曾经使用过。
博客示例包含以下表格:
Users
Posts
用户模型: $hasMany = array('Post'); Post 模型: $belongsTo = array('User');
我目前使用脚手架只是为了测试所有内容,但有一些自定义视图和用于 posts_controller 的自定义 add() 操作。
问题是当我对posts_controller 使用add() 操作时,用户的id 字段(来自Users 表)没有放入Posts 表的user_id 外键字段中。因此,当我显示帖子时,视图的“作者”部分是空白的,因为找不到 ID。如果我使用debug($posts)
,则返回的数组没有每个帖子的 user_id 的任何信息,因此“用户”数组中没有任何信息。
我认为 user_id 是在 cakePHP 表之间添加关联的传统方式,但它似乎不起作用。
有什么想法我需要做什么吗?
提前非常感谢,
英菲尼迪汽水
PS 对不起,如果我用 cakephp 问题让你不知所措。
聚苯乙烯
差点忘了,我的 add.ctp 帖子视图如下所示:
<div class="posts form">
<?=$form->create('Post');?>
<fieldset>
<legend>Add Post</legend>
<?
e($form->input('name'));
e($form->input('date'));
e($form->input('content'));
e($form->input('User'));
?>
</fieldset>
<?=$form->end('Submit');?>
</div>
<div class="actions">
<ul>
<li><?=$html->link(__('List Posts', true),array('action'=>'index'));?></li>
<li><?=$html->link(__('List Users', true),array('controller','users', 'action'=>'index'));?></li>
<li><?=$html->link(__('New User', true),array('controller'=>'users', 'action'=>'add'));?></li>
</ul>
</div>
post_controller.php 中的 add() 操作:
function add()
{
if(!empty($this->data))
{
$this->Post->create();
if($this->Post->save($this->data))
{
$this->Session->setFlash('The Post has been saved', true);
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('The Post could not be saved. Please try again.', true);
}
}
$users = $this->Post->User->find('list');
$this->set(compact('users'));
}