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

时间:2015-11-12 06:21:39

标签: php validation cakephp save

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

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

现在,我想要发生的是每次我向用户表添加数据时,它会检查要保存的数据是否已经存在于帐户表中,如果不存在则会闪现错误,否则它将保存。

我怎么能在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']);
    }

1 个答案:

答案 0 :(得分:0)

你可以通过这种方式解决它

在您的添加方法中,您可以使用您的请求数据检查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";
           }

}

我认为你得到了逻辑。