我試圖在以「保存相關模型數據(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表仍然爲空。 –