【发布时间】:2013-08-16 09:08:28
【问题描述】:
好的,所以我有两张桌子 Employee 和 User
我的员工模型如下所示:
class Employee extends AppModel{
public $name = 'Employee';
public $primaryKey = "employee_id";
public $actsAs = array('Containable');
public $belongsTo = array(
'User' => array(
'className' => 'User',
'dependent' => false,
'foreignKey' => 'user_id'
)
);
}
我的用户模型如下所示:
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
// ...
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('employee', 'client')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
}
在我的员工控制器中,我有一个允许员工添加其他员工的操作,该操作如下所示:
public function add() {
if ($this->request->is('post')) {
$this->Employee->User->create();
if ($this->Employee->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
我的员工表是这样的
employee_id user_id
现在,每当我添加用户时,用户都会正确添加到我的用户表中,并且我的 employee 表中也添加了一行,但是 employee 表中有两个错误:
employee_id是一个自动增量,这不会发生,它似乎一直覆盖 1。(因此我尝试创建的每个用户都是employee_id= 1)user_id始终为 0,但在用户表中,user_id 为例如 21。
谁能告诉我为什么会这样以及我该如何解决?
更新
我的员工控制器中的添加操作现在如下所示:
public function add() {
if ($this->request->is('post')) {
$this->Employee->User->create();
if ($this->Employee->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
我在我的用户模型中添加了一个 hasMany:
public $hasMany = array(
'Employee' =>array(
'className' => 'Employee',
'dependent' => true,
'foreignKey' => 'user_id'
)
);
还是没有变化
【问题讨论】:
标签: php cakephp cakephp-model