我有两个型号“Ficha”和“Perigo”:
class Ficha extends AppModel {
var $primaryKey = 'id_ficha';
public $validate = array(
'nome_produto' => array(
'rule' => 'notEmpty'
),
'versao' => array(
'rule' => 'notEmpty'
),
'data_ficha' => array(
'rule' => 'notEmpty'
)
);
}
class Perigo extends AppModel {
var $belongsTo = array(
'Ficha' => array(
'className' => 'Ficha',
'foreignKey' => 'id_fichas'
)
);
}
正如你所看到的那样,它们是“联系在一起的”。现在,在代码中我有一个Ficha的表单,FichasController的方法“add()”重定向到我的Perigo模型:
add()(FichaController)
public function add() {
//pr($this->request->data); // to get the data from the form
if ($this->request->is('post')) {
$this->Ficha->create();
if ($this->Ficha->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
//$last_id=$this->Ficha->getLastInsertID();
//$this->redirect(array('action' => 'preencher_ficha'),$last_id);
$this->redirect(array('controller'=>'perigos', 'action' => 'add'),$last_id);
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
重定向到PerigosController中存在的表单。
add.ctp(Perigo)
echo $this->Form->create('Perigo');
echo $this->Form->input('class_subst', array('label' => 'Classificação da substância ou mistura:'));
echo $this->Form->input('simbolos_perigo', array('label' => 'Símbolos de Perigo:'));
echo $this->Form->input('frases_r', array('label' => 'Frases R:'));
echo $this->Form->end('Avançar');
add()(PerigoController)
public function add() {
if ($this->request->is('post')) {
$this->Perigo->create();
if ($this->Perigo->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('controller'=>'perigos', 'action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
但是我不知道该怎么做。由于模型是关系型的,并且数据库中的两个表也是如此(表perigos有一个外键是表“fichas”的主键),我如何在数据库中的表perigos上插入数据?我的意思是,当我提交第二张表格时,如何将第一种形式的Ficha键插入“perigos”的外键?
答案 0 :(得分:1)
正如@mark所说,你的重定向很糟糕,它应该在URL数组中包含id
:
$this->redirect(array('controller'=>'perigos', 'action' => 'add', $last_id));
像这样,您通过URL传递参数。
在您add
的{{1}}行动中,您应该在该方法中使用PerigosController
参数:
$idFicha
表单中//PerigosController.php
public function add($idFicha){
//here you can use $idFicha
...
//when submiting the Perigos form, we add the foreign key.
if($this->request->is('post')){
//adding the foreign key to the Perigo's array to add in the DB.
$this->request->data['Perigo']['ficha_id'] = $idFicha;
if ($this->Ticket->save($this->request->data)) {
//...
}
}
}
方法提交的数据将始终包含在此类型的数组中:POST
。在你的情况下:
$this->request->data['Model_name']
另一种方法是,如果您希望隐藏$this->request->data['Perigo']
值,则使用会话:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#sessions