使用CakePHP保存关联模型

时间:2013-04-12 18:36:12

标签: cakephp-2.0

我正在尝试在http://book.cakephp.org/2.0/en/models/saving-your-data.html的示例代码中构建,该部分以“保存相关模型数据(hasOne,hasMany,belongsTo)”开头。但是,当我调用未设置时,我收到以下错误消息:

间接修改重载属性AppModel :: $ MealContent无效[APP \ Controller \ MealsController.php,第15行] 尝试修改非对象的属性[APP \ Controller \ MealsController.php,第15行]

当然,数据也不会保存。

如您所见,我的应用程序没有公司或帐户。相反,我有Meals和MealContents,但关系似乎已经设置相同。显然,某处存在问题,所以这里有一些代码。

Meals.php:

class Meals extends Entry {

    public $hasMany = 'MealContents';
    public $validate = array(
        'Timestamp' => array(
            'validDate' => array(
                'rule' => array('garbageDateChecker'),
                'required' => true,
                'message' => 'The date could not be understood.'),
            'noTimeTravel' => array(
                'rule' => array('noTimeTravel'),
                'required' => true,
                'message' => 'You cannot enter times in the future.')
        )
    );

}

MealContents.php:

class MealContents extends Entry {

    public $belongsTo = 'Meals';
    public $validate = array(
        'Meals_ID' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'required' => true,
                'message' => 'This field cannot be blank')
        ),
        'Item_ID' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'required' => true,
                'message' => 'This field cannot be blank')
        )
    );

}

最后,控制器的index()函数:

public function index() {
        $this->set('title_for_layout', "Food Log");
        if ($this->request->is('post')) {
            $this->Meal->create();

            unset($this->Meal->MealContent->validate['Meals_ID']);
            if ($this->Meal->saveAssociated($this->request->data)) {
                $this->Session->setFlash('The meal was logged.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash("Couldn't save the meal.");
            }
        }
    }

Entry.php

abstract class Entry extends AppModel {

    public function garbageDateChecker($dateToCheck) {
        date_default_timezone_set("America/Tijuana");
        $result = TRUE;

        try {
            new DateTime($dateToCheck['Timestamp']);
        } catch (Exception $e) {
            $result = FALSE;
        }

        return $result;
    }

    public function noTimeTravel($dateToCheck) {
        date_default_timezone_set("America/Tijuana");
        $result = TRUE;

        $objectifiedDateToCheck = new DateTime($dateToCheck['Timestamp']);
        $currentTime = new DateTime("now");

        if ($objectifiedDateToCheck > $currentTime) {
            $result = FALSE;
        }

        return $result;
    }

}

我很确定save()失败不是由于验证,因为即使我注释掉验证规则和unset()行,也不会保存数据。

很容易将其归咎于糟糕的数据或搞砸视图。但是,数据看起来还不错:

$this->request->data
--MealContents
---[0]
-----[Food_Item_ID] = "0"
--Meals
---[Comments] = ""
---[Timestamp]
-----[day] = "12"
-----[hour] = ...

当我阅读CakePHP书时,我错过了什么?

1 个答案:

答案 0 :(得分:1)

在所有模型类声明中,您应该扩展AppModel类而不是“Entry”。此外,您需要将模型名称更改为单数名词。用餐而不是用餐。

class Meal extends AppModel {

    //your model's code

}

class MealContent extends AppModel {

    //your model's code

}

在你的控制器中,如果你想跳过saveAssociated调用的验证,你可以传递一个options数组,元素“validate”设置为False作为第二个参数。你不应该在你的模型上使用unset,因为它会影响你应用的其余部分。

$this->Meal->saveAssociated($this->request->data, array("validate" => false));