2017-06-21 45 views
0

另一個表的數據我有這些表的CakePHP:更新更新

用戶表:

id lastname firstname email     company    city  phone 
1 Doe   John  [email protected]  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 

當我更新了一個用戶(changi在他們所屬的公司中),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')); 
} 
+1

爲什麼有公司名稱的用戶表開始?聞起來不夠正常化。 – ndm

+0

@ndm好耶,有一些問題的東西。我與公司名稱一致,但如果我要顯示我的表格,我需要獲取公司名稱,所以我不知道。實際上,我在我的用戶表中添加了一個company_id列,但不知道如何在顯示屏中收集名稱而不是想法 –

+0

ndm是正確的,如果您的模型已正確關聯,則自然會檢索公司信息(如名字),當你得到一個用戶時,不需要重複數據。你的手上有一個結構嚴謹的數據庫,問題不在於蛋糕。 –

回答

0

你好這裏是更新兩個表的簡單方法: 先在公司表的外鍵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 
    } 

     } 
} 

使用同樣的方法對公司表更新

+0

謝謝,你有什麼想法,當我在html中顯示用戶表時,如何顯示正確的公司名稱?我通過foreach循環在html表中顯示用戶表。所以用users表中的外鍵company_id,應該有一種方法來獲取名稱,對吧? –

+0

找到我的路!非常感謝 ! –

+0

@ Nolan.K所示的代碼是CakePHP 2.x的,請不要接受這樣的答案,這隻會混淆未來的讀者。 – ndm