Search code examples
cakephphas-and-belongs-to-manyrelationships

CakePHP HABTM relationship issue


I'm trying to create a social networking type of website where a user can send/receive a friend request. In our current system when a user sends a request half the required information is stored in the database then when a user accepts the rest of the information for the rest is inputted.

the relationships_users table is id, partyone, partytwo, expirydate, active

the problem im having is once a user accepts a request and puts in an expiry date, its inserted in a new column - not in the column relating to that user

here is my add function

    if($this->request->is('post')){
    $this->Relationship->create(); 
    if ($this->Relationship->save($this->request->data)) 
    { 
        $this->Session->setFlash('The relationship has been saved');  

    }
    else { $this->Session->setFlash('The relationship could not be saved. Please, try again.'); } 
    } 

  }

here is my approve function

if($this->request->is('post')){
        $this->Relationship->create(); 
        $this->Relationship->save($this->request->data);
        $this->Session->setFlash('The information has been saved');}
        else{$this->Session->setFlash('The information couldnt be saved');}

im assuming I've missed some simple code, any help would be appreciated its inserted in a new column - not in the column relating to that users relationship*


Solution

  • Your post doesn't the problem at whole, but what I understand you should follow some steps described below:

    • When first half of the info saved in Relationship table then you have to get the id of that entry and you can get like following:

      $this->Relationship->save($this->request->data);

      $lastId = $this->Relationship->id; // will gives you id of first half info saved

    • Then you have to embed that $lastId with the rest of the info i.e last half after request confirmation. If you can embed that ID to the second half info that is within $this->request->data, then $this->Relationship->save($this->request->data) will update the previous saved row. In that case, you don't need $this->Relationship->create();.

      According to cakePHP, if any data contains id within it, then instead of creating new row and save, it will update the corresponding row having that id.