我有这些表
用户表:
id lastname firstname email company city phone
1 Doe John doe.john@email.com somecompany New-York 85505040
公司表:
id name adress city phone
1 somecompany 1881 Paper Street New-York 85505042
2 anothercompany 18 Digital Street New-York 87505040
companies_users表:
id user_id companies_id
1 1 2
当我更新用户(更改他们所属的公司)时,companies_users表会更新companies_id。 cakephp应用程序是我固有的东西所以我不能轻易找到所有内容。
我要添加的是,当我更改公司表中的某些内容时,能够更新用户的公司:如果我更改了名称,我希望在用户表中更改名称。
CompaniesController编辑:
public function edit($id = null){
$companie = $this->Companies->get($id);
if ($this->request->is(['post', 'put'])) {
if ($this->Companies->save($companie)) {
$this->Flash->success(__('Your company has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your company.'));
}
}
UsersController编辑:
public function edit($id = null){
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data,['associated' => ['Companies']]);
if ($this->Users->save($user)) {
$this->Flash->success(__('Your user has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your user.'));
}
$this->set('user', $user);
$companies = $this->Users->Companies->find('list');
$this->set(compact('companies'));
}
答案 0 :(得分:0)
Hello这是更新两个表的简便方法: 首先在公司表中创建外键 user_id(int)(11)NULL 更新用户表时:
public function edit_user($id = null)
{
// check if id in empty or not
if(empty($id))
{
// redirect to list page
}
$this->User->id = $id;
if ($this->request->is('put') || $this->request->is('post')) {
if ($this->User->save($this->request->data))
{
$this->Companies = ClassRegistry::init('Companies');
$comp_id = $this->Companies->find('first',array(
'contain' => array(),
'fields' => array('Companies.id'),
'conditions' => array('Companies.user_id' => $id),
));
$this->Companies->id = $comp_id['Companies']['id'];
$this->Companies->savefield('name',$this->request->data['User']['company']);
// success message place here
}
else
{
// false message write
}
}
}
对公司表更新使用相同的方法