我得到了表Categories,我想通过id_category删除记录。我做错了什么?
index.ctp:
<?php
echo $this->Form->postLink(
'Delete',
array('action' => 'delete', $categories['Category']['id_category']),
array('confirm' => 'Are you sure?')
);
?>
类别控制器:
public function delete($id) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
$categories = $this->Category->findById_Category($id);
$this->Category->delete($categories['Category']['id_category']);
}
?>
findById_Category()不是有效的魔术查找器。
如文档所示,您需要使用正确的驼色大小写格式:
findByIdCategory()
但就我个人而言,我不会使用魔法探测器。我会使用普通的find(first)调用。
当您期望一个结果时,不要调用您的变量$categories
。这令人困惑。
最后但同样重要的是,"id_category"是非常非传统的。如果没有任何原因,请不要拘泥于惯例,在本例中,"category_id"是category模型/类别表的外键的字段名。
编辑上面的评论让我相信,在这里,您的非常规"id_category"字段实际上应该是该表的主键。这会使您的查找调用实际上甚至不正确,因为在这种情况下,您应该使用(链接的)文档将该字段正确映射为主键:
public $primaryKey = 'id_category';
但在这里,同样的事情也是正确的:如果没有合理的理由,不要使用"id_category",而是使用"id"。
无论哪种方式,您都可以直接使用
$this->Category->delete($id);
此外,在查找记录时:
$this->Category->findById($id); // No matter what the field actually is named
保存:
$this->Category->save($data);
$id = $this->Category->id; // It will always map to `->id` internally.
文档:http://book.cakephp.org/2.0/en/models/model-attributes.html#primarykey