我有两张桌子Users
和Clients
用户表敲击如下所示:
id (primary)
username(varchar)
password, client_id
现在我的客户表如下所示:
user_id, client_id(primary), is_new
它们之间的关系定义如下:
class User extends AppModel
{
public $name = 'User';
public $hasOne = array(
'Client' =>array(
'className' => 'Client',
'dependent' => true,
'foreignKey' => 'client_id'
)
);
}
class Client extends AppModel
{
public $name = 'Client';
public $primaryKey = 'client_id';
public $belongsTo = array(
'User' => array(
'className' => 'User',
'dependent' => true,
'foreignKey' => 'user_id'
)
);
}
现在在我的用户控制器中,我有以下保存操作:
if ($this->request->is('post')) {
$data = null;
$client_id = null;
if ($this->request->data['User']['group_id'] == 1) {
$client_id = 2;
} elseif ($this->request->data['User']['group_id'] == 2) {
$client_id = $this->request->data['User']['Client id'];
}
$data = array('User' => array(
'username' => $this->request->data['User']['username'],
'password' => $this->request->data['User']['password'],
'group_id' => $this->request->data['User']['group_id'],
'client_id' => $client_id),
'Client' => array('client_id' => $client_id)
);
if ($this->User->save($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.'));
}
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
当我保存一个新实体时,将使用正确的 client_id 添加到 users 表中,但没有将任何内容添加到 clients 表中。
谁能告诉我为什么会这样?
请注意,我已尝试将功能更改为saveAll();
更新
如果我执行以下操作:
$data = array( 'User' => array( 'username' => $this->request->data['User']['username'],
'password' => $this->request->data['User']['password'],
'group_id' => $this->request->data['User']['group_id'],
'client_id' => $client_id ),
'Client' => array('client_id' => $client_id) );
if ($this->User->Client->saveAll($data)) {
}
又名使用$this->User->Client->saveAll
而不是$this->User->saveAll()
一切正常..
现在这很好,但它应该是那样的吗?