I need help with creating the right relations between 3 tables in CakePHP. These are:
- users - pK = user_id
- books - pK = book_id
- books_users
I am trying to make my users_books-table contain all the relations between what book belongs to what user, and vica versa, like:
ID | user_id | book_id
--------------------------
1 321 231
2 24 58
3 80 58
4 24 75
5 80 231
My approach has been to make a hasAndBelongsToMany-relation, but when adding a new book the users_books-table does not get populated with any info.
In my controller I've tried the saveAll() and saveAssociated()-method but nothing works.
Can anybody help me with what association-code i should put in my Models to make this work?
public function addBook() {
$this->Book->create();
$this->request->data['Book']['book_user_id'] = $this->Auth->user('user_id');
$data = $this->request->data['Book'];
if (!$data['book_img']['name']) {
unset($data['book_img']);
}
if ($this->Book->saveAll($data)) {
$this->Session->setFlash(__('The book has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The book could not be saved. Please, try again.'));
}
}
The the new array:
$test = array('User' => $this->Auth->user('user_id'), 'Book' => $data);
pr($test);
Outputs this:
Array
(
[User] => 4
[Book] => Array
(
[book_study_id] => ha_fil
[book_title] => The title
[book_price] => 123
[book_isbn] => 123
[book_user_id] => 4
)
)
Thanks in advance, Jesper.
viewandcontrollercode also - Anil kumar