我有一个hasMany通过Course
, User
和CourseMembership
我正在尝试在课程视图上创建一个退订按钮。现在这是我的数组:
(
[Course] => Array
(
[id] => 1
[name] => Flying
[description] => Oh! The Magic!
[created] => 2014-03-05 14:45:21
[modified] => 2014-03-05 14:45:21
)
[Lesson] => Array
(
[0] => Array
(
[id] => 1
[title] => Growing Wings
[description] => Here's how you grow wings!
[course_id] => 1
[created] => 2014-03-05 14:19:38
[modified] => 2014-03-05 14:19:38
)
[1] => Array
(
[id] => 2
[title] => Taking Flight
[description] => You are finally ready to take flight.
[course_id] => 1
[created] => 2014-03-06 11:49:51
[modified] => 2014-03-06 11:49:51
)
)
[CourseMembership] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 4
[course_id] => 1
)
)
)
我设置了一个带有删除操作的CourseMemberships控制器。但是,我在课程中设置模型时遇到了问题,以区分coursememmembership的适当ID,其中user_id是登录用户(CakeSession::read("Auth.User.id");
),而课程是当前课程。
这是Courses的unsubscribe()控制器:
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->CourseMembership->delete(array('CourseMembership.user_id'=> $userid))) {
$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'));
}
编辑:这是我创建的退订链接。
<?php echo $this->Form->postLink(__('Unsubscribe'), array('controller' => 'CourseMemberships', 'action' => 'unsubscribe', $course['Course']['id'], CakeSession::read("Auth.User.id")), null, __('Are you sure you want to delete # %s?', $course['Course']['id'])); ?>
如果我理解正确的话,您想要删除登录用户的特定课程订阅。所以在课程控制器的退订操作中你可能会有这样的内容:
//课程控制器
public function unsubscribe($id = null){
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->Course->id = $id;
if (!$this->Course->exists()) {
throw new NotFoundException(__d('Course', 'Invalid course'));
}
if($this->Course->CourseMembership->unsubscribe($id, CakeSession::read('Auth.User.id'))){
$this->Session->setFlash(__d('Course', 'Unsubscribed!'));
$this->redirect(array('controller' => 'courses', 'action' => 'go_here_etc'));
}
$this->Session->setFlash(__d('Course', 'Attention! Not Unsubscribed!'));
$this->redirect(array('controller' => 'courses', 'action' => 'go_here_etc'));
}
// CourseMembership模型
public function unsubscribe($courseId, $userId){
// I assume that each user can subscribe only one time the same course. This calls the ids inputted in the unsubscribe link.
return $this->deleteAll(array('CourseMembership.course_id' => $courseId, 'CourseMembership.user_id' => $userId));
}