麻烦我的“喜欢”系统

时间:2012-09-28 13:46:35

标签: cakephp controller

所以,我在CakePHP项目中添加了一个“Like”系统,我有一点问题。当我想添加一个Like ...它根本就不会发生。这就是我所拥有的:

<?php 
  echo $this->Form->create("Like", array("url" => array("controller" => "likes", "action" => "like")));
  echo $this->Form->hidden("user_id",array(
    "value" => AuthComponent::user("id")
  ));
  echo $this->Form->hidden("post_id",array(
    "value" => $post["Post"]["id"]
  ));
  echo $this->Form->end();

  echo $this->Html->link(
    "<li><i class='icon-heart icon-large'></i> ".count($post["Like"])." likes</li>",
    "",
    array("escape" => false, "onclick" => "document.getElementById('LikeViewForm').submit();")
  );
?>

这是控制器:

<?php class LikesController extends AppController{

  function like() {
    $user_id = $this->Auth->user("id");
    if(!$user_id){
      $this->redirect("/");
      die();
    }
    if ($this->request->is("post")) {
      $d = $this->request->data;         
      $d["Like"]["id"] = null;
      if($this->Like->save($d,true,array("post_id","user_id"))){
        $this->redirect($this->referer());
      }
    }
  }

}

当我点击链接时,它会正确刷新页面,所以我假设表单已发送,但数据库中没有新内容......

有什么猜测吗?

1 个答案:

答案 0 :(得分:0)

对于新记录,您需要先使用create()。试试这个:

function like() {
    $user_id = $this->Auth->user("id");

    if (!$user_id) {
        $this->redirect("/");
        die();
    }

    if ($this->request->is("post")) {
        $this->Like->create();
        if ($this->Like->save($this->request->data, true, array("post_id", "user_id"))) {
            $this->redirect($this->referer());
        }
    }
}

希望这有帮助。