如何避免在保存数据时出错 - Cakephp
问题描述:
我正在使用Cakephp并试图加入一种方法来确保我们的预订系统不会让两个用户预订相同的约会。防爆。用户1打开约会,用户2同时打开它。用户1预约该预约。用户2试图预订它,但系统检查并发现它不再可用。如何避免在保存数据时出错 - Cakephp
我想这会发生在验证,或beforeSave(),但不知道如何去做。
现在我在模型中做了一个函数来从控制器调用。在控制器中,我有:
if ($this->Timeslot->checkIfNotAvailable()) {
$this->Session->setFlash('This timeslot is no longer available');
$this->redirect(array('controller' => 'users', 'action' => 'partner_homepage'));
}
,并在模型中我有这样的功能:
function checkIfNotAvailable($data) {
$this->recursive = -1;
$timeslot = $this->find('all', array(
'conditions' => array(
'Timeslot.id' => $this->data['Timeslot']['id'])
)
);
if ($timeslot['student_id'] == 0) {
//They can reserve it, do not spring a flag
return false;
} else {
//Throw a flag!
return true;
}
}
我觉得我混了使用自定义的验证,当它不叫了。这显然不起作用。有什么建议么?
谢谢!
答
如果你有什么工作,你可以坚持下去,你也可以尝试在你的模型中创建一个beforeValidate()回调函数。
class YourModel extends AppModel {
function beforeValidate(){
if(!$this->checkIfNotAvailable($this->data)) {
unset($this->data['YourModel']['time_slot']);
}
return true; //this is required, otherwise validation will always fail
}
}
这样你删除TIME_SLOT它去验证之前,它会在这一点上落验证错误,踢用户返回到编辑页面,并让他们选择不同的时间段,最好更新数据输入页面将不再具有可用的时隙。
您好史提夫,谢谢您的建议。我的方式现在不能正常工作......你看到我在用这种方法做什么时会出现任何错误? – tnichols 2011-05-04 00:26:50
我会尝试你现在的建议。 – tnichols 2011-05-04 00:27:01
您的尝试可能失败,因为您正在使用'find('all')'这将返回整个记录数组,这使得无法测试'$ timeslot ['student_id']'。 试着将它切换到一个'find('first')',你可能没问题。 – stevecomrie 2011-05-04 02:26:35