我有两种类型的用户:employees
和customers
我需要区分它们,所以我为它们创建了2个单独的表。然后我选择CakePHP作为我的框架,然后我想按照简单认证教程,其中有一个用户表。所以我决定创建这样的表:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`username` varchar(36) COLLATE utf8_czech_ci NOT NULL,
`password` varchar(36) COLLATE utf8_czech_ci NOT NULL,
`role` varchar(30) COLLATE utf8_czech_ci NOT NULL,
`name` varchar(30) COLLATE utf8_czech_ci NOT NULL,
`surname` varchar(40) COLLATE utf8_czech_ci NOT NULL,
`phone` varchar(16) COLLATE utf8_czech_ci NOT NULL,
`email` varchar(40) COLLATE utf8_czech_ci NOT NULL,
`employee_id` int(20) DEFAULT NULL,
`customer_id` int(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `EMAIL` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `customer` (
`id` int(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT AUTO_INCREMENT=1 ;
我的模特:
员工
public $hasOne = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'employee_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
用户:
public $belongsTo = array(
'Employee' => array(
'className' => 'Employee',
'foreignKey' => 'employee_id',
'conditions' => '',
'fields' => '',
'order' => ''
);
添加用户功能:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
$roles = array('admin', 'employee');
if (in_array($this->request->data['User']['role'], $roles)) {
if ($this->User->Employee->save($this->request->data))
$this->request->data['User']['employee_id'] = $this->User->Employee->getLastInsertId();
else {
$this->Session->setFlash(__('Employee could not be saved.'));
return;
}
}
else {
$this->User->Customer->save($this->request->data);
$this->request->data['User']['customer_id'] = $this->User->Customer->getLastInsertId();
$this->User->Customer->create();
}
if (!$this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
else {
$this->Session->setFlash(__('The user has been saved.'));
}
//return $this->redirect(array('action' => 'index'));
}
$employees = $this->User->Employee->find('list');
$customers = $this->User->Customer->find('list');
$this->set(compact('employees', 'customers'));
}
我感觉这个概念模型不对,因为Employee
和Customer
表只包含主键。
此外($this->User->Employee->save($this->request->data
)返回false
。是否存在CakePHP无法保存空模型的问题?
或者您对如何建模这些表格有更好的了解吗?
感谢。
答案 0 :(得分:0)
如果您打算获得特定于员工类型用户和客户类型用户的信息,那么您进入的方向很好,并且您将这些未来字段添加到客户和员工表中。如果您需要做的只是区分员工类型用户和客户类型用户,那么您只需要在用户表中的一个字段来区分类型,例如
is_employee tinyint(1) default 0,