2015-11-12 36 views
0

我目前在我的cakephp應用程序上工作我有數據庫名爲time,它有兩個表:users and accountsCakephp:檢查數據是否存在之前存在

users表有僱員和密碼數據字段 的accounts表也僱員,密碼等。

現在,我希望發生的是我每次添加數據時,用戶表,它會檢查如果要保存的數據已經存在於賬戶表中,如果沒有,則會閃爍錯誤,否則會保存。

我如何在cakephp中做到這一點?這裏是代碼:

add.ctp

public function add() 
    { 
     $user = $this->Users->newEntity(); 
     if ($this->request->is('post')) { 
      $user = $this->Users->patchEntity($user, $this->request->data); 
      if ($this->Users->save($user)) { 
       $this->Flash->success(__('Logs has been saved.')); 
       return $this->redirect(['action' => 'index']); 
      } else { 
       $this->Flash->error(__('The logs could not be saved. Please, try again.')); 
      } 
     } 
     $this->set(compact('user')); 
     $this->set('_serialize', ['user']); 
    } 
+0

採用了獨特的領域 http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules –

+0

這怎麼可能,如果我使用的唯一的字段它只是說要插入的數據必須是唯一的所有我想要發生的是在我的數據保存在表格中的用戶之前如果將檢查賬戶表中是否存在EmployeeId和密碼j – 123

+0

不介意你的評論不清楚你究竟是什麼想要嗎?如果你想創建所有獨特的領域然後做到這一點,請閱讀文檔。 –

回答

0

您可以通過這種方式

在add方法解決這個問題,你可以檢查你的Employid您的請求數據。

例如

if ($this->request->is('post')) { 

      $employid = $this->request->data('employid'); //make sure your field name 

      $this->loadModel('Your Employ model'); // add your employ model 
      $check = $this->Employ->find('count') 
            ->where(['Employ.employid' =>$employid ]); 
      if($check!=0){ 
      $user = $this->Users->patchEntity($user, $this->request->data); 
      if ($this->Users->save($user)) { 
       $this->Flash->success(__('Logs has been saved.')); 
       return $this->redirect(['action' => 'index']); 
       } else { 
        $this->Flash->error(__('The logs could not be saved. Please, try again.')); 
       } 
      } 
      else 
      { 
       echo "error message if not found"; 
      } 

} 

我想你的邏輯。