I have Users and I have Courses. I am trying to create a "Join" button for the users when they're viewing the course list in order to subscribe them to the Courses.
I was told to use
class Course extends AppModel
{
public $hasAndBelongsToMany = array('User');
}
and
class User extends AppModel
{
public $hasAndBelongsToMany = array('Course');
}
But I don't know how to implement the actual button and the posting of the info to a table called courses_users
Where do I implement this?
Thanks in advance!
You want to sent the student ID and the course ID to your saveAll()
method. You could do this through your courses controller as follows:
<?php
class CoursesController extends AppController {
public function join($courseId) {
$data = array(
'Course' => array(
'id' => $courseId
),
'Student' => array(
'id' => $this->Auth->user('id') // ID of logged in user
)
);
if ($this->Course->saveAll($data)) {
$this->Session->setFlash( __('Successfully joined course.'));
}
else {
$this->Session->setFlash( __('Error joining course.'));
}
$this->redirect('/');
}
}
This is just a simple example. You’ll need to tweak it to your app, and add any validation etc.
If you are this new I would suggest using the cake bake utility which will examine your tables , ask some questions about the relations and build the model, controller and views for all the basic create, update and delete operations in your database. You can then modify them for your needs. That's how I still do it to save lots of time.