如何删除cakephp中的记录

时间:2012-10-17 13:46:31

标签: cakephp

任何人都可以告诉我如何从数据库中删除记录吗? 我完成剩下的部分只删除遗骸。我正在运行删除命令但是 数据不会从数据库中删除。但是我在控制器(delete_user)中创建了一个动作,其中包含从数据库中删除用户的代码。 电子邮件值存储在会话中,我正在访问它; s值使用会话读取功能 在下一个控制器中。

function delete_user() { $email=$this->Session->read('User.email'); $this->User->delete($email, $cascade = true); echo $this->Session->delete('User.email'); echo $this->Session->delete('User.username'); $this->redirect(array('action' => 'login')); } );

我正在主页(查看)页面中创建一个链接。就像这样。

a href='/cakephp/cakephp/Users/delete_user'>Delete Profile</a>

我这样做是对还是错?

4 个答案:

答案 0 :(得分:6)

在提出这样的问题之前,请先查看在线documentation

更新18/10/12

尝试使用CakePhp的魔法查找类型:

$user = $this->User->findByEmail("bob@gmail.com");
$this->User->delete($user['User']['id']);

答案 1 :(得分:3)

在您的控制器中,使用删除操作替换以下代码:

public function delete($id = null) {
    if (!$this->request->is('post')) {
        throw new MethodNotAllowedException();
    }
    $this->User->id = $id;
    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid user'));
    }
    if ($this->User->delete()) {
        $this->Session->setFlash(__('User deleted'));
        $this->redirect(array('action' => 'index'));
    }
    $this->Session->setFlash(__('User was not deleted'));
    $this->redirect(array('action' => 'index'));
}

并在ctp文件中添加以下链接:

 <?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', ID OF THE RECORD, null, __('Are you sure you want to delete # %s?', ID OF THE RECORD)); ?>

然后你的问题就会解决......

答案 2 :(得分:1)

你只需要将id作为第一个参数传递:

$this->User->delete($id, $cascade);

答案 3 :(得分:0)

用这个你可以删除它而不用级联:

 $this->Todo->delete($this->request->data('Todo.id'));

你可以用

来加入这个目标
function beforeDelete(){

}

这是我的完整删除操作:

function delete($id = null){

     $this->Todo->recursive = 1;

            // new
            $todo = $this->Todo->read(null,$id);
            if($id == null || $todo == null) {
                $this->Session->setFlash('Todo existiert nicht.');
                $this->redirect(array('action' => 'index'));
                return;
            }
            $this->set('todo',$todo);
            $this->Todo->delete($this->request->data('Todo.id'));
            $this->redirect(array('action' => 'index'));
            return;


}