【发布时间】:2013-12-29 02:30:42
【问题描述】:
我有两个表 one 和 twos 我在“两个”表 two_one_id 中有一个外键 我想一次在两个表中插入数据,意味着在一个表单中插入数据,那么如何管理控制器和模型,我可以为此制作一个模型和一个控制器吗?那么如何为此创建模型和控制器 我应该为这两个表选择哪种类型的关系?
我做了两个不同的表格 One.php 和 Two.php 我做了两个控制器 OnesController.php 和 twosController.php 我可以在它们两个中使用脚手架并使用脚手架我可以在控制器和模型中的两个表中插入数据吗,如果可以使用脚手架,那么如何做到,或者在这段代码中我尝试过不使用脚手架,手动管理视图 * /
/*One.php 文件
public $displayField = 'name';
public $hasOne = array(
'Two' => array(
'className' => 'Two',
'foreignKey' => 'two_one_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
//Two.php
<?php
App::uses('AppModel', 'Model');
class Two extends AppModel {
public $displayField = 'sname';
public $belongsTo = array(
'One' => array(
'className' => 'One',
'foreignKey' => 'two_one_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
//OnesController.php
<?php
App::uses('AppController', 'Controller');
/**
* Ones Controller
*
* @property One $One
* @property PaginatorComponent $Paginator
*/
class OnesController extends AppController {
/**
* Helpers
*
* @var array
*/
public $helpers = array('Html','Form');
public $uses = array('One','Two');
public $components = array('Paginator');
public function index() {
$this->One->recursive = 0;
$this->set('ones', $this->Paginator->paginate());
}
public function view($id = null) {
if (!$this->One->exists($id)) {
throw new NotFoundException(__('Invalid one'));
}
$options = array('conditions' => array('One.' . $this->One->primaryKey => $id));
$this->set('one', $this->One->find('first', $options));
}
public function add() {
if ($this->request->is('post')) {
$this->One->create();
if ($this->One->save($this->request->data)) {
$this->Session->setFlash(__('The one has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The one could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
if (!$this->One->exists($id)) {
throw new NotFoundException(__('Invalid one'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->One->save($this->request->data)) {
$this->Session->setFlash(__('The one has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The one could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('One.' . $this->One->primaryKey => $id));
$this->request->data = $this->One->find('first', $options);
}
}
public function delete($id = null) {
$this->One->id = $id;
if (!$this->One->exists()) {
throw new NotFoundException(__('Invalid one'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->One->delete()) {
$this->Session->setFlash(__('The one has been deleted.'));
} else {
$this->Session->setFlash(__('The one could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
【问题讨论】:
-
如果您尝试从同一个表单创建 2 个新模型(即一个新的
One和一个新的Two),并同时关联它们,我想您会必须这样做:首先保存One对象,通过$this->One->getLastInsertId();获取ID,使用我们刚刚找到的id保存Two对象以创建关联。
标签: cakephp