我正在关注一个应用程序的教程,用户可以在其中上传文件并且文件属于特定用户。用户和上传之间存在 HABTM 关系,如下所示:
上传.php:
var $hasAndBelongsToMany = array(
'SharedUser' => array(
'className' => 'User',
'joinTable' => 'uploads_users',
'foreignKey' => 'upload_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting'
)
);
用户.php:
var $hasMany = array(
'Upload' => array(
'className' => 'Upload',
'foreignKey' => 'user_id',
'dependent' => false
)
);
var $hasAndBelongsToMany = array(
'SharedUpload' => array(
'className' => 'Upload',
'joinTable' => 'uploads_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'upload_id',
'unique' => true
)
);
一切似乎都可以正常工作,但有一个例外,那就是在创建新的 Upload 时,uploads_users 表没有更新。如果我手动将数据插入其中,那么旨在使用它功能查找和显示数据的视图。谁能提出什么问题?
这是 uploads_users 表:
+-----------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| upload_id | char(36) | NO | | NULL | |
| user_id | char(36) | NO | | NULL | |
+-----------+----------+------+-----+---------+----------------+
我已经从教程中稍微更改了 add Upload 方法(因此如果数据库保存失败,它会删除上传的文件),所以这里也是:
function add() {
if (!empty($this->data)) {
$this->Upload->create();
if ($this->uploadFile()) {
try {
if (!$this->Upload->saveAll($this->request->data)) {
throw new Exception('Couldn't save to database.');
}
$this->Session->setFlash(__('The upload has been saved', true));
$this->redirect(array('action' => 'index'));
}
catch (Exception $e) {
unlink(APP . 'tmp/uploads/' . $this->request->data['Upload']['id']);
$this->Session->setFlash(__('The upload could not be saved: ' . $e->getMessage(), true));
}
} else {
$this->Session->setFlash(__('The upload could not be saved.', true));
}
}
$users = $this->Upload->User->find('list');
$this->set(compact('users', 'users'));
}
function uploadFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$id = String::uuid();
if (move_uploaded_file($file['tmp_name'], APP.'tmp/uploads'.DS.$id)) {
$this->request->data['Upload']['id'] = $id;
$this->request->data['Upload']['user_id'] = $this->Auth->user('id');
$this->request->data['Upload']['filename'] = $file['name'];
$this->request->data['Upload']['filesize'] = $file['size'];
$this->request->data['Upload']['filemime'] = $file['type'];
return true;
}
}
return false;
}