Cakephp:保存前检查数据是否存在

Cakephp:保存前检查数据是否存在,php,validation,cakephp,save,Php,Validation,Cakephp,Save,我目前正在开发我的cakephp应用程序,我的数据库名为time,它有两个表:users和accounts users表包含EmployeeId和Password数据字段 accounts表还包含EmployeeId、密码等 现在,我想做的是每次我向users表添加数据时,它都会检查accounts表中是否已经存在要保存的数据,如果不存在,它将闪烁错误,否则它将保存 我如何在cakephp中实现这一点?以下是代码: 添加.ctp public function add() {

我目前正在开发我的cakephp应用程序,我的数据库名为
time
,它有两个表:
users和accounts

users
表包含EmployeeId和Password数据字段
accounts
表还包含EmployeeId、密码等

现在,我想做的是每次我向users表添加数据时,它都会检查accounts表中是否已经存在要保存的数据,如果不存在,它将闪烁错误,否则它将保存

我如何在cakephp中实现这一点?以下是代码:

添加.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']);
    }

你可以用这种方法解决它

在add方法中,您可以使用请求数据检查
员工ID

比如说

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";
           }

}

我想你明白逻辑。

使用唯一字段怎么可能?如果我使用唯一字段,它只会说要插入的数据必须是唯一的。我希望发生的一切是在我的数据保存到表中之前,用户如果要检查accounts表中是否也存在EmployeeId和密码,请不要介意,您的评论不清楚实际是什么你想要什么?如果您想创建唯一的所有字段,请阅读文档。检查链接以获得更好的解释添加您的Add.ctp employid字段。是cakephp 2版还是3版?