我知道如何在理论上做到这一点,但我不确定如何执行。
我有两张桌子,我正在做婚礼登记
用户表 [id] [用户名] [限制] [参加]
旅客 [ID] [USER_ID] [名称]
限制是他们可以拥有多少来宾,而user_id是外键
这是我的添加功能 在View控制器中,
public function add($id = null) {
if ($this->request->is('post')) {
$this->Guest->create();
if(//sudo code $['User']['limit'] >= $['Guest']*Count)
{
$this->Session->setFlash(__('error you can\'t add anymore'));
return $this->redirect(array('controller' => 'Users', 'action' => 'view' , $id));
} else {
if ($this->Guest->save($this->request->data)) {
$this->Session->setFlash(__('Guest added'));
return $this->redirect(array('controller' => 'Users', 'action' => 'view' , $id));
} else {
$this->Session->setFlash(__('Invalid name entered'));
return $this->redirect(array('controller' => 'Users', 'action' => 'view' , $id));
}
}
}
//或者我接近这一切都错了我应该在模型中这样做?
答案 0 :(得分:1)
使用验证。
访客属于用户。
Guest.php
public $validate = array(
//other fields
'user_id' => array(
//other rules for user_id field
'limit' => array(
'rule' => 'checkGuestLimit'
'message' => 'Some error message'
)
)
);
public function checkGuestLimit() {
$userLimit = $this->User->find('first', array(
'conditions' => array(
'User.id' => $this->data['Guest']['user_id']
),
'fields' => array(
'User.limit'
)
));
$guestCount = $this->find('count', array(
'conditions' => array(
'Guest.user_id' => $this->data['Guest']['user_id']
)
));
if ($guestCount >= $userLimit['User']['limit']) {
return false;
}
return true;
}
答案 1 :(得分:0)
public function add($id = null) {
if ($this->request->is('post')) {
$user_id = $this->Auth->user('id');
$guest_count = $this->Guest->find('count', array(
'conditions' =>
array('user_id' => )
)
);
$guest_limit = $this->Auth->user('limit');
if($guest_count >= $guest_limit)
{
$this->Session->setFlash(__("error you can't add anymore"));
return $this->redirect(array('controller' => 'Users', 'action' => 'view' , $id));
} else {
$this->Guest->create();
if ($this->Guest->save($this->request->data)) {
$this->Session->setFlash(__('Guest added'));
return $this->redirect(array('controller' => 'Users', 'action' => 'view' , $id));
} else {
$this->Session->setFlash(__('Invalid name entered'));
return $this->redirect(array('controller' => 'Users', 'action' => 'view' , $id));
}
}
}
}