Creating new record if the id is not in db

776 views Asked by At

I am working on a cakephp 2.x , I want to create a new row or record if the userid is not present in db otherwise update the record, but the problem is: it is not updating the current record. It is creating the record with the userid "0" I dont know the problem is. If is not finding the record it should create a record with the userid which I am giving.

public function activeNoStatus(){


    $this->loadModel('Status');
    $userid =  $this->request->data('idUser');
    $notify =  $this->request->data('notify');

    $data = array();
    $data['activeNo'] = $notify;




    $count =  $this->Status->findUserId($userid);
    if($count>0){
        $this->Status->id = $userid;
        $this->Status->save($data);


        echo "update";
    }else{
             //create new row
          $datanew=array();
         $this->Status->id = $userid;
         $this->request->data['Status']['activeNo']=$notify;

          $this->Status->save($this->request->data);
          echo "ok";
    }



}
1

There are 1 answers

0
Arash Mousavi On

It seems idUser field is not autoincrement, In cakePHP documentaion :

All tables with which CakePHP models interact (with the exception of join tables), require a singular primary key to uniquely identify each row. If you wish to model a table which does not have a single-field primary key, CakePHP’s convention is that a single-field primary key is added to the table. You have to add a single-field primary key if you want to use that table’s model.

Rather than using an auto-increment key as the primary key, you may also use char(36). Cake will then use a unique 36 character uuid (String::uuid) whenever you save a new record using the Model::save method.

So you should make idUser autoincrement Primary key.