如何一天只更新一次数据?

时间:2016-12-26 05:27:34

标签: php cakephp cakephp-2.0

我面临一个问题。我正在使用Cakephp2.0 Framework。我希望 searchcount 每天更新一次。例如: -

这是我的代码:

Starting serachcount = 0;
if it access today(26dec 2016) means n number of times its count will 
be **serachcount** = 1;

If it is not  access by tomorrow (27dec 2016) its count should not be 
 updated its still **serachcount** = 2;
And this process carries on

任何人都可以帮助我,这是我的功能

以下是我尝试过的代码

public function visits($id=null){
        $this->loadModel('User');
        if($this->request->is('post')){
            $data= $this->request->data;
            $id = $data['id'];
            $userdata = $this->User->find('first',array(
                'conditions'=>array('User.id'=>$id),
                'fields'=>array('id','searchcount')
                )
            );
            $this->User->id = $id;
            $searchcount = $userdata['searchcount'];
            $searchcount = $searchcount+1;
            $this->User->saveField('searchcount',$searchcount);
            echo $searchcount; die;
        }
    }

1 个答案:

答案 0 :(得分:1)

你只需要@Ayaou提到的简单逻辑:

1. add field in your table eg. count_date 
2. do not forget to update count_date when searchcount get updated
3. make your visits function something like this:

if($this->request->is('post')){
 $data= $this->request->data;
 $id = $data['id'];
 $userdata = $this->User->find('first',array(
   'conditions'=>array('User.id'=>$id),
   'fields'=>array('id','searchcount','count_date')
            )
        );
  $this->User->id = $id;
  $searchcount = $userdata['searchcount'];
  $countDate = $userdata['count_date'];
  $dateToday = date('Y-m-d');
  if($countDate != $dateToday) {
     $dataToUpdate["count_date"] = $dateToday;
     $dataToUpdate["searchcount"] = $searchcount+1;
     $this->User->save($dataToUpdate);
   } else {
     // already updated today
   }
 }