This method of linking models allows you to have a single table of data, say Comment, that is related to any one of a number of other Models (eg: Post, Event).
The Models
Before we get started, lets setup the models.
models/comment.phpclass Comment extends AppModel {
var $name = 'Comment';
}
var $name = 'Comment';
}
models/event.php
The Controller
Now to save the data.
views/posts/view.ctp
controllers/posts_controller.php
class PostsController extends AppController {
var $name = 'Posts';
function view($id = null) {
if (!$id) {
$this->_flash(__('Invalid Post.', true),'error');
$this->redirect(array('action'=>'index'));
}
// save the comment
if (!empty($this->data['Comment'])) {
$this->data['Comment']['class'] = 'Post';
$this->data['Comment']['foreign_id'] = $id;
$this->Post->Comment->create();
if ($this->Post->Comment->save($this->data)) {
$this->_flash(__('The Comment has been saved.', true),'success');
$this->redirect(array('action'=>'view',$id));
}
$this->_flash(__('The Comment could not be saved. Please, try again.', true),'warning');
}
// set the view variables
$post = $this->Post->read(null, $id); // contains $post['Comments']
$this->set(compact('post'));
}
}
var $name = 'Posts';
function view($id = null) {
if (!$id) {
$this->_flash(__('Invalid Post.', true),'error');
$this->redirect(array('action'=>'index'));
}
// save the comment
if (!empty($this->data['Comment'])) {
$this->data['Comment']['class'] = 'Post';
$this->data['Comment']['foreign_id'] = $id;
$this->Post->Comment->create();
if ($this->Post->Comment->save($this->data)) {
$this->_flash(__('The Comment has been saved.', true),'success');
$this->redirect(array('action'=>'view',$id));
}
$this->_flash(__('The Comment could not be saved. Please, try again.', true),'warning');
}
// set the view variables
$post = $this->Post->read(null, $id); // contains $post['Comments']
$this->set(compact('post'));
}
}
In Conclusion
That's all there is to it, now you can save comments related to any other model record!










Post new comment