Cakephp更正多个孩子的正确方法

时间:2014-06-12 12:04:46

标签: cakephp

在我的情况下,问题对象有多个答案。这是问题数组。

Array
(
    [Question] => Array
        (
            [id] => 15
            [questionary_id] => 11
            [type] => MULTIPLE
            [body] => What activity do you do?
            [is_deleted] => 
        )

    [Answer] => Array
        (
            [0] => Array
                (
                    [id] => 8
                    [question_id] => 15
                    [body] => Basketball
                    [is_correct] => 1
                )

            [1] => Array
                (
                    [id] => 9
                    [question_id] => 15
                    [body] => Softball
                    [is_correct] => 1
                )

            [2] => Array
                (
                    [id] => 10
                    [question_id] => 15
                    [body] => Snooker
                    [is_correct] => 0
                )

        )
)

现在我想删除垒球,将斯诺克重新命名为shoker并添加板球作为新答案。保存问题后,下面的数组将。

Array
(
    [Question] => Array
        (
            [id] => 15
            [questionary_id] => 11
            [type] => MULTIPLE
            [body] => What activity do you do?
            [is_deleted] => 
        )

    [Answer] => Array
        (
            [0] => Array
                (
                    [id] => 8
                    [question_id] => 15
                    [body] => Basketball
                    [is_correct] => 1 
                )            

            [1] => Array
                (
                    [id] => 10
                    [question_id] => 15
                    [body] => Shoker
                    [is_correct] => 0
                )

            [2] => Array
                (
                    [id] => 15
                    [question_id] => 15
                    [body] => Cricket
                    [is_correct] => 0
                )

        )
)

最好的方法是什么?我可以删除所有答案并添加新答案。 cackphp有点羽毛吗?

1 个答案:

答案 0 :(得分:0)

我找不到解决方案。所以我删除了旧孩子并添加了新的孩子,如下所示。

$this->Question->id = $id;

if ($this->Question->save($this->request->data)) {

    $this->loadModel('Answer');

    $this->Answer->deleteAll(array('question_id' => $id));          

    $this->Answer->saveMany($answers);

    $this->Session->setFlash(__('The question has been saved.'), 'default', array(
        'class' => 'alert alert-success'
    ));

    return $this->redirect(array('action' => 'index', $qId));
} else {
    $this->Session->setFlash(__('The question could not be saved. Please, try again.'), 'default', array(
        'class' => 'alert alert-danger'
    ));
}