我正在尝试在我的CakePHP(1.3)应用程序中使用FileUpload
插件(https://github.com/webtechnick/CakePHP-FileUpload-Plugin)。
我有两种型号:PendingContract
和 PendingContractFile
.一个PendingContract
可以有许多PendingContractFile
记录。保存新PendingContract
时,我也想保存上传的PendingContractFile
;但是,我的保存方法失败了,因为PendingContract
还没有 ID,并且在我的 PendingContractFile
中用作外键。
为清楚起见,以下是我的模型:
<?php
class PendingContract extends AppModel {
var $name = 'PendingContract';
var $belongsTo = array(
'Supplier'
);
var $hasMany = array(
'PendingContractFile'
);
}
class PendingContractFile extends AppModel {
var $name = 'PendingContractFile';
var $belongsTo = array(
'PendingContract' => array(
'className' => 'PendingContract',
'foreignKey' => 'pending_contract_id'
),
'Author' => array(
'className' => 'User',
'foreignKey' => 'author_id'
)
);
}
这是我保存PendingContract
的控制器方法:
<?php
class PendingContractsController extends AppController {
function add() {
if (!empty($this->data)) {
if ($this->FileUpload->success) {
$this->Session->setFlash('Pending contract successfully created.');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash($this->FileUpload->showErrors());
}
}
}
}
目前我收到的错误是:
1452: 无法添加或更新子行:外键约束失败(pending_contract_files,外键 (pending_contract_id) 引用pending_contract_files_ibfk_1 pending_contracts (ID) 在更新级联上删除级联) 时
)
如何使用 FileUpload
插件,以便它将上传的文件与我的新PendingContract
记录附加?
我看了一下插件,它似乎不会将发布的数据与上传的文件一起保存。它有目的地将上传文件数据与表单中的任何其他输入分开,并为每个文件执行保存。
就个人而言,我会尝试其他插件,例如不依赖于任何控制器级代码的插件,例如 https://github.com/josegonzalez/upload 插件。
public function beforeSave($options = array()) {
if (!isset($this->data[$this->alias][$this->primaryKey])) {
$this->data[$this->alias][$this->primaryKey] = String::uuid();
}
return parent::beforeSave($options);
}
这将在保存之前为记录生成新的 UUID。您可能只应在尚未设置密钥时才执行此操作。
我遇到了类似的问题,我所做的是在您的情况下添加新的 PendingContractFile 时取消设置验证。因此,在使用 saveAll 方法之前,请尝试添加:
unset($this->PendingContract->PendingContractFile->validate['pending_contract_id']);
所以它不会检查foreign_key。希望对您有所帮助。