-1

我想在这里理解的是,这个错误是什么意思,我做错了什么?我一定是搞砸了命名约定。

我的模型是产品和类别。类别有hasMany,产品有belongsTo。

http://webdesign4.georgianc.on.ca/~100141468/comp2084/todo/products/add

http://webdesign4.georgianc.on.ca/~100141468/comp2084/todo/products/filter/9

名字y

通过 y

产品控制器

function filter($category_id) {
            $this->set('Product',$this->Product->findAllByCategoryId($category_id));
        }

添加

$this->loadModel('Category');
$this->set('Categorys',$this->Category->find('list',array('order'=> array('Category.name'))));

过滤器.ctp

<? foreach($Product as $row): ?>
     <tr><td>
<?=$row['Product']['id']?>
</td><td>
<?=$row['Product']['name']?>
</td><td>
<?=$row['Product']['price']?>
</td><td>
<?=$row['Category']['name']?>
</td><td>
<a href="edit/<?=$row['Product']['id']?>">Edit</a>
    </td></tr>
<? endforeach; ?>

添加.ctp

<?php
        echo $this ->Form->input('name');
        echo $this ->Form->input('description');
        echo $this ->Form->input('price');
        echo $this ->Form->input('file', array('type' => 'file'));
        echo $this ->Form->input('Category_id');
        echo $this ->Form->end('submit',true); 
        ?>
4

2 回答 2

2

首先做一个debug($Product);你看到Category钥匙了吗?如果没有,要么将递归设置得更高,甚至更好地使用Containable.

对于您的添加,将视图变量名称categories更改为并将表单输入字段更改为category_id(也就是说,如果您在数据库中遵循了约定,那只是一个错字)

如果类别与产品相关,则不需要loadModel.

简单地做$this->Product->Category->find...

于 2012-07-23T20:26:05.800 回答
1

这很简单……你没有掌握蛋糕的基本原理。我建议再次阅读本书和教程,重点关注命名约定和关联。

您需要这些关联:

//product.php
var $belongsTo = array(
    'Category' => array(
        'className' => 'Category',
        'foreignKey' => 'category_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ));


// category.php
var $hasMany = array(
    'Product' => array(
        'className' => 'Product',
        'foreignKey' => 'category_id'
    )
);



// products_controller.php
function filter($category_id) {
    $this->set('products', $this->Product->findAllByCategoryId($category_id));
}

function add() {
    if (!empty($this->data)) {
        $this->Product->create();
        if ($this->Product->save($this->data)) {
            $this->Session->setFlash(__('The Product has been saved', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The Product could not be saved. Please, try again.', true));
        }
    }
    $categories = $this->Product->Category->find('list');   
    $this->set(compact(array('categories')));
}

   // filter.ctp
   debug($products); // just to see what data has been returned

   // add.ctp
   echo $this->Form->create('Product');
   echo $this->Form->input('name');
   echo $this->Form->input('description');
   echo $this->Form->input('price');
   echo $this->Form->input('file', array('type' => 'file'));
   echo $this->Form->input('category_id'); // categories
   echo $this->Form->end('submit',true); 

清除缓存,这应该可以工作。

于 2012-07-23T21:43:06.720 回答