我正在构建一个简单的机制,用户可以通过点击链接来查看帖子。我正在使用GET而不是POST,因为我想允许通过URL触发该方法。
据说如何使用GET保存数据?由于此方案中不存在请求数据...我的模型如下所示:
class Like extends AppModel
{
public $name = 'Like';
public $belongsTo = array('User','Post');
}
和添加方法如下:
public function add( $id )
{
$post = $this->Post->find('first', array(
'conditions' => array('Post.id'=>Tiny::reverseTiny($id))
));
if (!$post)
{
throw new NotFoundException('404');
}
if($post['Post']['user_id'] == $this->Auth->user('id'))
{
$this->Session->setFlash('You can\'t like your own post... That\'s just silly!');
}
if ($this->Like->create())
{
$liked = $this->Like->find('first', array(
'conditions' => array('Like.id'=>Tiny::reverseTiny($id), 'Like.user_id'=>$this->Auth->user('id') )
));
if(!$liked){
$this->Like->saveField('user_id', $this->Auth->user('id'));
$this->Like->saveField('post_id', $post['Post']['id']);
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('You already like this post!');
}
else
{
$this->Session->setFlash('Server broke!');
}
}
有人可以帮忙吗?
<?php echo $this->Html->link('1', array('controller'=>'followers','action'=>'add','id'=>Tiny::toTiny($post['Post']['id'])),
array('title'=>'Follow','class'=>'follow')); ?>
这部分一切正常。它正在GET中保存一个我正在努力争取的新行。
答案 0 :(得分:1)
您好,您只需要建立一个指向您的控制器操作的链接,并在网址中传递您的变量。
要明确帖子中的链接是否在您的帖子视图中: $ this-&gt; Html-&gt; link('喜欢这篇文章',数组('controller'=&gt;'喜欢','action'=&gt;'add',$ postId))
它应该呈现如下链接: www.yourWebSite / likes / add / 1喜欢postId 1,
操作(添加)后的变量被解释为控制器操作的变量
如果您的功能添加
public function add($postId, $wathever){
}
网址应该像www.yourWebSite / likes / add / 1 / blabla 其中1是add动作的第一个var,第二个是blabla,依此类推。
这相当于非重写网址:?postId = 1&amp; whatever = blabla
编辑:
if(!$liked){
//simulate the post behaviour
$this->request->data['Like']['user_id'] = $this->Auth->user('id');
$this->request->data['Like']['post_id'] = $post['Post']['id'];
//save the data
if ($this->Like->save($this->request->data)) {
$this->Session->setFlash(__('Thanks for your support !'));
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('Server broke!');
}
}
答案 1 :(得分:1)
如何使用save with id=0
代替create
?
<?php
$like = array(
"Like" => array
(
"id" => 0,
"user_id" => $this->Auth->user("id"),
"post_id" => $post['Post']['id']
)
);
$result = $this->Like->save($like);
if(!$result){$this->Session->setFlash('Server broke!');}
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
?>