删除CakePHP中的深层关联

时间:2014-03-17 03:47:07

标签: cakephp

我有一个Courses模型,它给了我这个数组:

[User] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [username] => itaita
                    [password] => sdfasdgadgadfgsfdgsdgsdgsdgdsg
                    [email] => itaita@xyz.com
                    [name] => 
                    [role] => admin
                    [hash_change_password] => 
                    [created] => 2014-03-16 21:06:48
                    [modified] => 2014-03-16 21:06:48
                    [CoursesUser] => Array
                        (
                            [id] => 1
                            [user_id] => 4
                            [course_id] => 1
                        )

                )

        )

我想创建一个订阅/取消订阅按钮,删除CoursesUser id=this user idcourse_id = this course,但我不知道如何从课程控制器和视图中访问它。

目前我有:

public function unsubscribe($id = null) {
        $this->Course->id = $id;
        $userid = CakeSession::read("Auth.User.id");

        if (!$this->Course->exists()) {
            throw new NotFoundException(__('Invalid course'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Course->User->delete(array('CoursesUser.user_id'=> $userid), false)) {
            $this->Session->setFlash(__('The course has been deleted.'));
        } else {
            $this->Session->setFlash(__('The course could not be deleted. Please, try again.'));
        }
        return $this->redirect(array('action' => 'index'));
    }

但这会删除用户。

我知道问题出在此处:$this->Course->User->delete但我不知道如何更改此问题以解决CoursesUser数组问题。

帮助!

1 个答案:

答案 0 :(得分:0)

你可以用这个:

$ this-> Course-> User-> CoursesUser-> deleteAll(array('CoursesUser.user_id'=> $ user_id,'CoursesUser.course_id'=> $ id),false);

基本上,假设您正确设置了模型关系,这将仅删除与您从auth检索到的user_id匹配的CoursesUser行,这些行也提供了对该操作提供的course_id。