我正在尝试更改我的编辑操作,以便用户只能编辑自己的帖子。
以下是我更改之前的编辑操作:
function edit($id = null) {
$this->Post->id = $id;
if (empty($this->data)) {
$this->data = $this->Post->read();
} else {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
然后这就是我尝试做的事情,但没有成功:
function edit($id = null) {
if ($this->Auth->user('id') == $this->Post->user_id) {
$this->Post->id = $id;
if (empty($this->data)) {
$this->data = $this->Post->read();
} else {
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
}
} else {
$this->Session->setFlash('You are not authorized to edit that post.');
$this->redirect(array('action' => 'index'));
}
}
有谁知道如何实现我想要的功能? CakePHP的自动化是否有更简单的方法来实现这一目标?
答案 0 :(得分:0)
public function edit($id) {
$post = $this->Post->find('first', array(
'conditions' => array('Post.id' => $id, 'Post.user_id' => $this->Auth->user('id')),
'recursive' => -1
));
if (!$post) {
$this->cakeError('error404');
}
if ($this->data) {
$this->data['Post']['id'] = $id;
if ($this->Post->save($this->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
} else {
$this->data = $post;
}
}