0

我是 cakephp 的新手。我有一个“用户”表和一个“类别”表

user belongsTo category (fields: users.id, users.name, users.category) category hasMany users (fields: category.id, category.name, users.category)

我正在处理这样的关联数据。

在(用户)edit.ctp 我把

// view/Users/edit.ctp

    echo $this->Form->input('name');
    echo $this->Form->input('categories', array( 'value' => $this->Form->value('User.category'), 
'name'=>'data[User][category]') );
</pre>

in users controller I have
<pre>
    public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
        }
        $sexes = $this->User->Sex->find('list');
        $categories = $this->User->Category->find('list');
        $this->set(compact('categories'));

    }

一切正常,但我怀疑有一种更简单的方法可以完成该表格。这真的需要吗?
, array( 'value' => $this->Form->value('User.category'), 'name'=>'data[User][category]')
没有这些参数,选择框不会高亮选中选项,并没有保存任何内容。

可能是这样的

echo $this->Form->input('Category.name');

例如?但是这样的代码不会显示选择框。
而且它不保存 users.category 字段。

我无法找到任何带有示例的教程或代码。链接将不胜感激。

4

1 回答 1

0

尝试对数据库表和字段使用 Cake 的命名约定。如果您遵循约定,Cake 将为您完成很多繁重的工作:

用户表:

users.id, users.name, users.category_id

类别表

categories.id, categories.name

用户模型

class User extends AppModel {

    public $belongsTo = array(
        'Category'
    );

}

类别模型

class Category extends AppModel {

    public $hasMany = array(
        'User'
    );

}

用户控制器:

class UsersController extends AppController {

    public function edit($id) {

        if (!empty($this->request->data) {

            // form submitted - try to save
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('User updated');
            }
            else {
                $this->Session->setFlash('Please correct the errors');
            }
        }
        else {
           // prepopulate the form
           $this->request->data = $this->User->findById($id);
        }

        // populate the categories dropdown
        $this->set('categories', $this->User->Category->find('list');

    }

}

/app/views/Users/edit.ctp

<?php

echo $this->Form->create();
echo $this->Form->inputs();
echo $this->Form->end('Update');
于 2013-02-06T14:30:46.473 回答