PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 21, 2022

[FIXED] How to delete a sub record based on criteria in Cakephp?

 April 21, 2022     cakephp, cakephp-2.0, cakephp-2.1, cakephp-2.3     No comments   

Issue

I have 2 tables "Topic" and "Post" linked in the model by hasMany

I want to delete the Post entry with id = 3 since it doesn't have a message.

In the model for table "Post", I have this "beforeSave" :

public function beforeSave($options = array()) {

  if ($this->data['Post']['message'] == '') {
    CODE TO DELETE HERE
  }
}

This is my $this->request->data :

Array
(
[Topic] => Array
(
    [id] => 1
    [topic_title] => This is my topic
)

[Post] => Array
(
    [1] => Array
        (
            [id] => 1
            [title] => Blah
            [message] => My message
        )

    [2] => Array
        (
            [id] => 2
            [title] => Second Blah
            [message] => Second My message
        )
    [3] => Array
        (
            [id] => 3
            [title] => Second Blah
            [message] => 
        )
    )
)

I can't figure out how to delete in the model or is this the wrong approach ?

I've now also tried this in the controller before saveAssociated :

$this->loadmodel('Post');

foreach ($this->request->data['Post'] as $i => $post) {

 if ($post['message'] == '') {
     unset($this->request->data['Post'][$i]);

     $options = array( 'conditions' => array( 'Post.id' => $i) );
     $this->Post->find('first', $options);

     if ($this->Post->delete()) {
      echo "Post id : " . $i . ' - Deleted';
    } else {
      echo "Post id : " . $i . ' - Not deleted';
    }
 }

}

This gives me "Post id xxx Deleted" however the Post record isn't deleted.


Solution

Since I'm using "saveAssociated" I also have to "unset" the post in "$this->request->data" otherwise it will be saved again.

$this->loadmodel('Post');

foreach ($this->request->data['Post'] as $i => $post) {

 if ($post['message'] == '') {
   unset($this->request->data['Post'][$i]);

 if ($this->Post->delete($post['id'], false)) {
  echo "Post id : " . $i . ' - Deleted';
 } else {
  echo "Post id : " . $i . ' - Not deleted';
 }
}


Answered By - flaggalagga
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing