我试图在以“保存相关模型数据(hasOne,hasMany,belongsTo)”开头的部分中的示例代码http://book.cakephp.org/2.0/en/models/saving-your-data.html上构建。但是,当我调用unset时,出现以下错误消息:使用CakePHP保存相关模型
重载属性的间接修改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')
)
);
}
最后,控制器的指数()函数:
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有什么我错过了什么?
其实,我扩展AppModel。我在帖子中加入了Entry类来演示。我会留下关于您的其他建议的其他意见。 –
我宁愿避免关闭所有验证。 –
虽然餐桌现在正确地增加了一行,但Meal_Contents表仍然为空。 –