好的,所以我有两张表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'
)
);
仍然没有变化
答案 0 :(得分:1)
一些问题......
1)您的employees表的主键应该是id,而不是employee_id。根据cakephp约定 - http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html
,主键始终命名为id2)正如您在Employee模型中有belongsTo一样,您还应该为您的用户模型添加一个hasOne关系 - 请参阅http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
3)为了保存记录及其相关数据,您需要的方法是saveAll
- 请查看此处的文档:http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array