2015-11-12 110 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"; 
      } 

} 

我想你的逻辑。

相关问题