如何根据Cakephp中的条件删除子记录?

时间:2016-10-20 14:17:38

标签: cakephp cakephp-2.0 cakephp-2.3 cakephp-2.1

我有2张桌子"主题"和"发布"由hasMany链接在模型中

我想删除id为3的帖子条目,因为它没有消息。

在桌子" Post"的模型中,我有这个" beforeSave" :

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

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

这是我的$ 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] => 
        )
    )
)

我无法弄清楚如何在模型中删除,或者这是错误的方法?

我现在也在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';
    }
 }

}

这给了我" Post id xxx Deleted"但是邮政记录没有被删除。

2 个答案:

答案 0 :(得分:0)

如果邮件为空,您可以取消设置beforeSave中的数据:

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

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

答案 1 :(得分:0)

因为我正在使用" saveAssociated"我也必须" unset"帖子在" $ this-> request-> data"否则会再次保存。

$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';
 }
}