【问题标题】:Cakephp: check if data exist before savingCakephp:在保存之前检查数据是否存在
【发布时间】:2015-11-12 06:21:38
【问题描述】:

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

users 表包含 EmployeeId 和 Password 数据字段 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']);
    }

【问题讨论】:

  • 如果我使用唯一字段,那怎么可能账户表 j 中也存在密码
  • 不介意您的评论不清楚您到底想要什么?如果您想创建所有字段唯一,请执行此操作,请阅读文档。
  • 检查链接以获得更好的解释i66.tinypic.com/rc58hh.png
  • 添加您的 add.ctp 的employid 字段。是 cakephp 2 还是 3 版本?

标签: php validation cakephp save


【解决方案1】:

你可以这样解决

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

}

我想你明白了。

【讨论】:

    猜你喜欢
    • 2018-12-26
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多