CakePHP:过滤器和外键!不工作

时间:2012-07-23 20:20:34

标签: cakephp filter foreign-key-relationship

我想在这里理解的是,这个错误意味着什么,我做错了什么?我必须搞砸命名惯例。

我的模特是产品和类别。类别包含hasMany,产品具有belongsTo。

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

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

姓名

传递y

的ProductsController

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'))));

filter.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; ?>

add.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); 
        ?>

2 个答案:

答案 0 :(得分:2)

首先执行debug($Product);您是否看到Category密钥?如果不是,则设置递归更高或甚至更好地使用Containable

对于您的添加,将视图var名称更改为categories并将表单输入字段更改为category_id(即如果您在数据库中遵循惯例,那只是一个错字)

如果类别与产品相关,则无需loadModel

只需$this->Product->Category->find...

答案 1 :(得分: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); 

清除缓存,这应该可行。