我正在尝试在http://book.cakephp.org/2.0/en/models/saving-your-data.html以“保存相关模型数据(hasOne,hasMany , 属于)”。但是,当我调用 unset 时,我收到以下错误消息:
重载属性 AppModel::$MealContent 的间接修改无效 [APP\Controller\MealsController.php,第 15 行] 尝试修改非对象的属性 [APP\Controller\MealsController.php,第 15 行]
自然,数据也不会被保存。
如您所见,我的应用程序没有公司或帐户。相反,我有 Meals 和 MealContents,但关系似乎已建立相同。显然,虽然某处存在问题,但这里有一些代码。
膳食.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.')
)
);
}
膳食内容.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.");
}
}
}
入口.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 的书时,我错过了什么?