我目前正在开发我的cakepp应用程序,我有一个名为time
的数据库,它有两个表:users and accounts
。
users
表具有EmployeeId和Password数据字段accounts
表中还有EmployeeId、Password等
现在,我想做的是,每次我将数据添加到用户表时,它都会检查要保存的数据是否已经存在于帐户表中,如果不存在,它将闪烁错误,否则它将保存。
我怎么能在蛋糕里做到这一点?这是代码:
添加.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']);
}
您可以通过这种方式解决
在添加方法中,您可以使用请求数据检查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";
}
}
我想你明白道理了。