我在Mysql中有两个表:
1- 物品
列:ID、名称、价格、category_id、已创建
2- 类别
列: ID, 名称, 已创建
类别有许多项目,项目属于类别:
Class Item extends AppModel {
public $belongsTo = 'Category';
}
lass Category extends AppModel {
public $hasMany = 'Item';
}
我想编辑一个给定的项目,因此我想显示可能的类别名称来选择一个。
View/Items/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');
?>
控制器/项目控制器.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 号。
您需要在控制器中设置一个$categories
变量;
$this->set('categories', $this->Item->Category->find('list'));
来自这里的文档
假设用户具有并且属于许多组。在控制器中,使用选择选项设置一个 camelCase 复数变量(在本例中为 group -> groups,或 ExtraFunkyModel -> extraFunkyModels)。在控制器操作中,您将输入以下内容:
$this->set('groups', $this->User->Group->find('list'));
在视图中,可以使用以下简单代码创建多项选择:
echo $this->Form->input('Group');
如果要在使用"属于"或"具有一个"关系时创建选择字段,则可以将以下内容添加到用户控制器(假设用户属于"组"):
$this->set('groups', $this->User->Group->find('list'));
然后,将以下内容添加到窗体视图中:
echo $this->Form->input('group_id');