【发布时间】:2016-03-14 09:17:24
【问题描述】:
我正在使用 CakePHP 2.5.1 开发一个 Web 应用程序。我在将外键保存在数据库中并在网页中显示相关数据时遇到问题。我有用户、经理、客户、房屋、地址和电子邮件表。
他们的关系是,
- 一个经理可以有很多客户,
- 一个客户可以有很多房子,
- 一个经理可以有很多地址,很多电子邮件,
- 一个客户可以有很多地址,很多电子邮件,
- 一个房子可以有很多地址
我的要求是,
- 经理是用户
- 注册后,经理将添加多个客户。针对每个客户,经理将添加多个房屋。
- 每个用户/经理都有一个个人资料/索引页面,其中将列出其所有客户。
- 每个客户都有一个个人资料/索引页面,其中将列出其所有房屋。
现在,我可以保存所有数据了。但是在数据库中,没有保存外键,从而在显示关联数据时产生了问题。例如,当manager注册完成时,将manager_id保存在addresses表中;但 customer_id 和 house_id 仍然为 NULL。为经理添加客户时,将customer_id保存在addresses表中;但 manager_id 和 house_id 仍然为 NULL。但是,它应该保存 manager_id,因为客户属于经理。同样,当为客户添加房屋时,它会将house_id保存在addresses表中;但 manager_id 和 customer_id 仍然为 NULL。但是,它应该保存 manager_id 和 customer_id,因为房子属于客户,而客户属于经理。
在 AppController 中,我定义了如下关系:
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authenticate' => array('Form' => array(
'contain' => array(
'Manager' => array(
'Address' , 'Email' , 'Customer' => array('House')))
在用户控制器中,我使用了以下方法:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->saveAll($this->request->data, array('deep' => true))) {
$components = array('Session');
$this->Session->setFlash('Welcome!');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(
__(' Please, try again.')
);
}
}
在CustomersControllers中,我使用了以下方法:
public function AddCustomer() {
if ($this->request->is('post')) {
$this->Customer->create();
if ($this->Customer->saveAll($this->request->data, array('deep' => true))) {
$primaryKey = $this->Customer->id;
$components = array('Session');
$this->Session->setFlash('Customer DATA have been saved!');
return $this->redirect(array('action' => ‘index'));
}
$this->Session->setFlash(
__('The Customer Data could not be saved. Please, try again.')
);
}
}
在 HousesControllers 中,我使用了以下方法:
public function AddHouse() {
if ($this->request->is('post')) {
$this->House->create();
$this->loadModel('House');
$houseData = $this->data['House'];
$houseData[‘house_id'] = $primaryKey;
if ($this->House->saveAll($houseData)) {
$components = array('Session');
$this->Session->setFlash(‘House DATA have been saved!');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(
__('The House Data could not be saved. Please, try again.')
);
}
}
在用户控制器中使用 add() 时,它使用外键保存用户和管理器数据。即 manager_id 作为外键保存在用户表中。但类似的函数 addCustomer() 和 addHouse() 不保存外键。客户表应将 manager_id 保存为外键,而 house 表应将 customer_id 保存为外键。因为他们的关系就像——经理有很多客户有很多房子。为什么这些类似的功能在这里表现不同?谁能给我任何提示,为什么没有保存外键?
【问题讨论】:
-
需要手动保存外键,因为外键是在父表数据保存时产生的,需要手动保存每张表的数据。
-
@Tony stark,怎么做?因为,当用户使用应用程序时,他们将无法手动将数据插入表中。
-
你有一些常识。手动表示手动将数据保存在表中。加载每个模型并传递数据数组进行保存。像这样: $saveData = $this->data; $this->loadModel('User'); $this->User($saveData); $userId = $this->用户->id; $managerData = 任何数据; $manager['user_id'] = $userId;//外键 $this->loadModel('Manager'); $this->Manager->保存($manager);
-
好的,谢谢。你太棒了。
-
你的伟大。干草@Tom 我可以把我的答案放在答案标签中吗?所以你可以标记为已回答,这样对我有帮助
标签: mysql cakephp-2.0