【问题标题】:CakePHP associations messing upCakePHP 关联搞砸了
【发布时间】:2010-08-09 13:28:57
【问题描述】:

我是 cakephp 新手,一直在阅读 Apress 书籍“Beginning CakePHP from Novice to Professional”,但在烘焙章节之后遇到了问题。

(如果你看过我最近提出的另一个问题,你就会知道我不得不跳过那一章,因为我无法让烘焙控制台在我的 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 的表之间添加关联的传统方式,但它似乎不起作用。

任何想法我需要做什么?

非常感谢,

英菲尼迪汽水

附:如果我对 cakephp 问题感到不知所措,请大家见谅。

P.P.S

差点忘了,我的 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>

还有posts_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'));
}

【问题讨论】:

    标签: mysql cakephp foreign-keys associations cakephp-1.3


    【解决方案1】:

    我也是蛋糕新手,但据我所知,我认为您应该在 add.ctp 中更改它:

    $form->input('User')
    

    到这里

    $form->input('user_id')
    

    formhelper 负责将输入显示为下拉列表(基于 hasMany-belongsTo 引用)。

    【讨论】:

    • 啊,那行得通,非常感谢,我只是假设这会下拉 user_id 值,例如 1、2、3 等,但确实行得通。那是我/你发现的那本书的第一个错误,最好圈那个:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2010-10-15
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多