我在尝试将复选框值插入到我的一个数据库表中时遇到问题。 我有一个表用户,服务和类别都与users表相关联。如何在表单中插入所有选中的复选框以保存到服务表中,然后检索它们? 我可以显示复选框以及服务名称,但不保存它们。
add.ctp
echo this->Form->select('service_id',$services,array('multiple'=>'checkbox'));
usersController.php
if ($this->request->is('post')) {
$this->User->create();
//debug($this->request->data);
//die();
$this->request->data['User']['role'] = 'user';
if ($this->User->saveAll($this->request->data)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$services = $this->User->Service->find('list');
$categories =$this->User->Category->find('list',array('fields'=>'category'));
$this->set(compact('categories','services'));
}
user.php
public $hasMany = array(
'Service' => array(
'className' => 'Service',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
一旦我运行了debug(),这就是我得到的:
services.php
public $displayField = 'name';
public $validate = array(
'name' => array(
'notBlank' => array(
'rule' => array('notBlank'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'selected' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'service_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
/*public $hasAndBelongsToMany = array(
'Platillo' => array(
'className' => 'Service',
'joinTable' => 'users_services',
'foreignKey' => 'user_id',
'associationForeignKey' => 'service_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);*/