gpt4 book ai didi

mysql - 蛋糕PHP : update another table's data on update

转载 作者:行者123 更新时间:2023-11-29 18:45:40 25 4
gpt4 key购买 nike

我有这些表

用户表:

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

当我更新用户(更改他们所属的公司)时,companys_users 表会更新companys_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.'));
}

}

用户 Controller 编辑:

 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'));
}

最佳答案

您好,这是更新两个表的简单方法:首先在公司表中创建外键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
}

}
}

使用相同的方法更新公司表

关于mysql - 蛋糕PHP : update another table's data on update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44676651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com