2014-11-14 44 views
0

我在MySQL两个表:项目(CakePHP的)

1项

列:ID,名称,价格,CATEGORY_ID,创建

2-分类

列:id,名称,创建日期

类别有很多项目和项目属于类别:

Class Item extends AppModel { 
    public $belongsTo = 'Category'; 
} 

lass Category extends AppModel { 
    public $hasMany = 'Item'; 
} 

我想编辑一个给定的项目,因此我想显示可能的类别名称来选择一个。

查看/项目/ edit.ctp

<h1>Edit Post</h1> 
<?php 
    echo $this->Form->create('Item'); 
    echo $this->Form->input('name'); 
    echo $this->Form->input('price'); 
    echo $this->Form->input('category_id'); 
    echo $this->Form->input('created'); 
    echo $this->Form->input('id', array('type' => 'hidden')); 
    echo $this->Form->end('Save Post'); 
?> 

控制器/ ItemsController.php

public function edit($id = null){ 
     if (!$id) { 
      throw new NotFoundException(__('Invalid Item')); 
     } 
     $item = $this->Item->findById($id); 

     if (!$item) { 
      throw new NotFoundException(__('Invalid Item')); 
     } 

     if (!$this->request->data) { 
      $this->request->data = $item; 
     } 

     if ($this->request->is(array('post', 'put'))) { 
      $this->Item->id = $id; 
      if ($this->Item->save($this->request->data)) { 
       $this->Session->setFlash(__('Your item has been updated.')); 
       return $this->redirect(array('action' => 'index')); 
      } 
      $this->Session->setFlash(__('Unable to update your item.')); 
     } 
    } 

的问题是:在形式CATEGORY_ID我看不到任何东西,甚至类别ID数。

回答

0

你需要设置控制器中的$categories变量;

$this->set('categories', $this->Item->Category->find('list')); 
+0

谢谢,它现在的工作! – 2014-11-15 14:13:48

0

从文档here

假设用户hasAndBelongsToMany组。在您的控制器中,使用select选项设置camelCase复数变量(在这种情况下为组 - >组,或ExtraFunkyModel - > extraFunkyModels)。在控制器动作,您会把下列内容:

$this->set('groups', $this->User->Group->find('list')); 

而且多选择可以用这个简单的代码来创建视图:

echo $this->Form->input('Group'); 

如果你想同时使用,以创建一个选择字段属于关联 - 或hasOne - 关系,你可以添加以下到您的用户控制器(假设你的用户属于关联集团):

$this->set('groups', $this->User->Group->find('list')); 

之后,添加以下到您的表单视图:

echo $this->Form->input('group_id');