我正在关注一个tutorial的应用程序,用户可以上传属于特定用户的文件和文件。用户和上传之间存在HABTM关系,如下所示:
upload.php的:
var $hasAndBelongsToMany = array(
'SharedUser' => array(
'className' => 'User',
'joinTable' => 'uploads_users',
'foreignKey' => 'upload_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting'
)
);
user.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
)
);
所有似乎都有效,但有一个例外,即在创建新的上传时,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 | |
+-----------+----------+------+-----+---------+----------------+
我已经从教程中稍微改变了添加上传方法(因此如果数据库保存失败,它会删除上传的文件),所以这里也是如此:
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;
}
答案 0 :(得分:1)
查看您的请求中的其他内容>数据会很有用。 如在cookbook中所写,您应该使用相关的模型结构。
它应该看起来如下:
$this->request->data['Upload']['id'] = $id;
$this->request->data['Upload']['user_id'] = $this->Auth->user('id');
...
$this->request->data['SharedUser']['id'] = $this->Auth->user('id');
此外,我看不到您的方法“uploadFile”中显示的belongsTo关系。也许你在“上传”模式中不需要它。