晚上好!我对CakePHP的魔力有点困惑。有些很神奇,但有一点让我困惑。我有一个用户模型,和一个相关的UserBasicInfo模型:
class User extends AppModel {
public $name = 'User';
public $hasOne = array(
'UserBasicInfo' => array(
'className' => 'UserBasicInfo',
'dependent' => true
)
);
class UserBasicInfo extends AppModel {
public $useTable = 'users_basic_info';
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'id'
)
);
联想是好的,它自动加入什么的。我如何告诉UserBasicInfo模型它的ID是什么,如果它有一个记录,当做插入?它可能并不总是有记录,因为我不强制用户添加此信息,并且我不喜欢添加充满空白数据的记录的想法。下面是我UserController中edit_basic_information方法:
public function edit_basic_information($id = null) {
$this->User->id = $this->Auth->user('id');
$test = $this->User->read();
echo '<pre>';
print_r($test);
echo '</pre>';
if (!$this->User->exists())
throw new NotFoundException(__('Invalid user'));
//if(empty($this->data))
// $this->data = $this->User->findById($this->User->id);
if ($this->request->is('post')) {
// $success = false;
$this->request->data['User']['id'] = $this->Auth->user('id');
// $duplicate = $this->User->find('first',
// array(
// 'conditions' =>
// array(
// 'UserBasicInfo.user_id' => $this->Auth->user('id')
// )
// )
// );
echo '<pre>';
print_r($this->request->data);
echo '</pre>';
// if($duplicate) {
// $success = $this->User->updateALL($this->request->data);
// } else {
$success = $this->User->saveALL($this->request->data, array('deep' => true));
// }
if ($success) {
$this->Session->setFlash(__('The info has been saved'));
} else {
$this->Session->setFlash(__('The info could not be saved. Please, try again.'));
}
}
$this->set('countries', $this->ChoicesCountries->find('list'));
}
正如你在上面看到的,我试过一些方法。蛋糕有这么大的魔力,做一些像额外的数据库调用来重复检查的事情让我觉得我做错了什么。还有,这个-
在进一步阅读CakePHP文档之后,我意识到这是一个有点愚蠢的问题。save/saveALL方法仅与我提供给它们的请求数据不符,这些数据将只包含我在视图中指定的字段。它不会随意向请求中添加数据-
我通过更改模型中的primaryKey(这不是问题的一部分,但在我找到解决方案后导致了问题),然后添加
$this->request->data['UserBasicInfo']['user_id'] = $user['UserBasicInfo']['user_id'];
对方法进行了修改。