我正在使用CakePHP 2.6.7。CakePHP 2.6.7 hasMany數據不保存
用戶將能夠添加到他的個人資料多個汽車和多個地址。他還可以將多個地址鏈接到一輛車,並將一個地址鏈接到多輛車。
然後我有一個用戶模式:
class User extends AppModel {
public $hasMany = array(
'Car',
'Address'
);
}
與汽車型號:
class Car extends AppModel {
public $belongsTo = array(
'User'
);
public $hasAndBelongsToMany = array(
'Address' =>
array(
'unique' => 'keepExisting'
)
);
}
的一個地址模式:
class Address extends AppModel {
public $hasAndBelongsToMany = array(
'Car' =>
array(
'unique' => 'keepExisting',
),
);
public $belongsTo = array(
'User'
);
}
我有一個表格,以便用戶可以編輯他的汽車(目前只有一輛):
[...]
<legend>Mes voitures</legend>
<?php
for($nbrvoiture = 0; $nbrvoiture <= 0; $nbrvoiture++)
{
?><h3>Voiture <?php echo $nbrvoiture+1?></h3><?php
$myLabelOptions = array('text' => "Marque");
echo $this->Form->input('Car.'.$nbrvoiture.'.CarMake', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));
$myLabelOptions = array('text' => "Modèle");
echo $this->Form->input('Car.'.$nbrvoiture.'.CarModel', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));
$myLabelOptions = array('text' => "Plaque d'immatriculation");
echo $this->Form->input('Car.'.$nbrvoiture.'.NumberPlate', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));
echo $this->Form->submit("Valider", array(
'class' => 'btn btn-default col-sm-offset-2'
));
}
的事情是,我無法將數據保存到我的數據庫。 這裏是用戶控制器代碼的一部分:
function edit() {
// On récupère l'ID de l'utilisateur
$user_id = $this->Auth->user('id');
// Si l'utilisateur n'a pas d'ID => il n'est pas connecté => il ne peut pas éditer son profil
if(!$user_id){
$this->redirect('/');
die();
}
debug($this->User->find('all'));
$this->User->id = $user_id;
$passError = false;
if($this->request->is('put') || $this->request->is('post')){
$d = $this->request->data;
$d['User']['id'] = $user_id;
debug($d);
if($this->request['pass'][0]=='cars')
{
if($this->User->saveAssociated($d, array('deep' => true))){
$this->Session->setFlash(__("Les informations sur la voiture ont bien été modifiées"), 'alert', array (
'plugin' => 'BoostCake',
'class' => 'alert-success'
));
}else{
$this->Session->setFlash(__("Impossible de modifier ou d'ajouter les infos"), 'alert', array (
'plugin' => 'BoostCake',
'class' => 'alert-danger'
));
}
}
當我保存數據,它示出了錯誤。
在我的數據庫我有這4個表:
Users(id, username, mail, password, created, lastlogin, active, firstname, lastname, gender, birthdate, phonenumber)
Cars(id, CarMake, CarModel, NumberPlate, user_id)
Addresses(id, address, city, state, postcode, country, user_id)
Addresses_cars(address_id, car_id)
這是什麼,我可以從形式獲得(在$ d變量)的例子:
array(
'Car' => array(
(int) 0 => array(
'CarMake' => 'Allard',
'CarModel' => '2005',
'NumberPlate' => '56QDS1'
)
),
'User' => array(
'id' => '1'
)
)
我不理解爲什麼它不起作用... 你能幫我嗎?
謝謝! :)
編輯:我也試過用SaveAll,但我無法得到它的工作..有什麼不對?
「它顯示錯誤」,但是你不會列出錯誤。你遇到了什麼錯誤? – Dave
它顯示我選擇在失敗時顯示的錯誤($ this-> Session-> setFlash(__(「Impossible de modifier ou d'ajouter les infos」))無論如何,問題解決了,它是驗證規則對於另一種與此相沖突的表單 –
這不是一個錯誤 - 這是一條信息。對於將來的問題,請確保在描述中準確,幷包含實際的錯誤/信息,以免浪費人們的時間想要幫助你。 – Dave