2014-11-14 47 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');