一次将数据保存在cakephp hasmany中,并且属于associate Association [英] Save data in a cakephp hasmany and belongsto association at once
问题描述
我知道这里经常问这个问题,但我也尽力遵循我提供的最佳解决方案。当我学习cakephp时,某些解决方案似乎很难在代码中实现。我正在使用cakephp 2.5。
I know this question is asked here a many times but I also tried to follow the solutions provided at my best. As I am learning a cakephp some solutions seemed difficult to implement in a code. I am using cakephp 2.5.
我要做的是创建一个包含一个或多个上载内容的问题报告。这是到目前为止我已经实现的一些功能:-
What I am trying to do is creating a problem report with attached one or more uploads. Here is some of what I have implemented so far:-
我有以下模型:
- 候选
- CandidatesProblemReport
- CandidatesProblemReportsUpload
有以下关联:
-
CandidatesProblemReport hasManddatesProblemReportsUpload
CandidatesProblemReport hasMany CandidatesProblemReportsUpload
候选者有很多CandidatesProblemReport
Candidate hasMany CandidatesProblemReport
CandidatesProblemReport属于候选者
CandidatesProblemReport belongsTo Candidate
CandidatesProblemReportsUpload属于To CandidatesProblemReport
CandidatesProblemReportsUpload belongsTo CandidatesProblemReport
Candidate.php
<?php
class Candidate extends AppModel {
public $name = 'Candidate';
public $hasMany = array(
'CandidatesProblemReport' => array(
'className' => 'CandidatesProblemReport',
'foreignKey' => 'candidate_id'
)
);
}
CandidatesProblemReport.php
<?php
class CandidatesProblemReport extends AppModel {
public $name = "CandidatesProblemReport";
public $belongsTo = array(
'Candidate' => array(
'className' => 'Candidate'
)
);
public $hasMany = array(
'Uploads' => array(
'className' => 'CandidatesProblemReportsUpload'
),
'Replies' => array(
'className' => 'CandidatesProblemReportsReply'
)
);
}
CandidatesProblemReportsController.php
class CandidatesProblemReportsController extends AppController {
public $name = "CandidatesProblemReports";
// ############# Report a Problem #############
// ********************************************
public function create() {
$userid = $this->Auth->user('id'); // Grabs the current user id
$this->set('userId', $userid); // Sends the current user id to the form
if ($this->request->is('post') && !empty($this->request->data)):
$this->CandidatesProblemReport->create();
$report = $this->CandidatesProblemReport->save($this->request->data);
if (!empty($report)):
$this->request->data['CandidatesProblemReportsUpload']['candidates_problem_report_id'] = $this->CandidatesProblemReport->id;
endif;
if ($this->CandidatesProblemReport->saveAssociated($this->request->data)):
$this->Session->setFlash('Your report has been submitted '
. 'successfully. Thank you!');
$this->redirect(array(
'action' => 'viewall')
);
else:
$this->Session->setFlash('Your report could not be submitted, '
. 'please try again');
endif;
endif;
}
}
create.ctp
<h1>Create a report</h1>
<?php
echo $this->Form->create('CandidatesProblemReport', array('type' => 'file'));
echo $this->Form->input('CandidatesProblemReport.report_subject');
echo $this->Form->input('CandidatesProblemReport.report_handle_department', array(
'options' => array(
'Technical' => 'Technical',
'Sales' => 'Sales',
'Support' => 'Support',
'Other' => 'Other'
)
));
echo $this->Form->input('CandidatesProblemReport.report_description');
echo $this->Form->input('CandidatesProblemReport.report_date', array(
'type' => 'hidden',
'value' => date('Y-m-d H:i:s'))
);
echo $this->Form->input('CandidatesProblemReport.candidate_id', array(
'type' => 'hidden',
'value' => $userId)
);
?>
<div>
<p><strong>Upload Screenshot/Files</strong></p>
<hr>
</div>
<?php
echo $this->Form->input('CandidatesProblemReportsUpload.0.report_upload', array(
'type' => 'file'
));
?>
<button class="add-new-upload" type="button">Add more</button>
<?php
echo $this->Form->end('submit');
echo $this->Html->script('jquery-2.1.1.min.js');
?>
<script type="text/javascript">
var i = 1;
$('.add-new-upload').click(function () {
$('.file').append('<input type="file" name="data[CandidatesProblemReportsUpload]['
+ i +
'][report_upload]" id="CandidatesProblemReportsUpload'
+ i +
'ReportUpload">');
i++;
});
</script>
现在发生的事情是我能够保存主模型数据,即CandidatesProblemReports,但是当我保存关联数据时
Now what is happening is I am able to save the main model data i.e. CandidatesProblemReports but when I saveAssociated data it again saves the main model creating second duplicate entry but the uploads are not getting saved.
推荐答案
通过关联保存数据
这是预期的行为, saveAssociated()
并不是只保存相关记录,它将主记录保存为好吧,所以您应该只使用 saveAssociated()
,无需手动设置外键,等等,CakePHP会自动执行。
Saving data with associations
That's the expected behavior, saveAssociated()
is not ment to save only the associated records, it will save the main record as well, so you should use saveAssociated()
only, no need to manually set the foreign key, etc, CakePHP will do that automatically.
控制器
public function create() {
// ...
if ($this->request->is('post') && !empty($this->request->data)):
$this->CandidatesProblemReport->create();
if ($this->CandidatesProblemReport->saveAssociated($this->request->data)):
// ...
endif;
endif;
}
记住别名
未创建上传记录的原因是,您在表单/数据中使用的别名不正确,您已将别名设置为上传
,但是在您的表单中,您使用的是 CandidatesProblemReportsUpload
,因此CakePHP将忽略此数据。
Mind your aliases
The reason for your upload records not being created, is that you are not using the proper alias in your form/data, you've set the alias to be Uploads
, but in your form you are using CandidatesProblemReportsUpload
, and so CakePHP will ignore this data.
表单
echo $this->Form->input('Uploads.0.report_upload', array(
'type' => 'file'
));
<script type="text/javascript">
var i = 1;
$('.add-new-upload').click(function () {
$('.file').append('<input type="file" name="data[Uploads]['
+ i +
'][report_upload]" id="Uploads'
+ i +
'ReportUpload">');
i++;
});
</script>
存储文件数据
注释中,CakePHP不会开箱即用地处理文件上传数据,您必须事先准备好它,例如,将其存储在磁盘上,然后模型存储文件的路径。
Storing file data
As mentioned in the comments, CakePHP doesn't handle file upload data out of the box, you'll have to prepare it in beforehand so that it is for example being stored on disk, and the model stores the path to the file.
虽然上面的代码通常可以正常工作,但它很可能会触发错误,因为它将尝试将文件上传数组存储在数据库中,而不是在平面数据中存储。
While the above code should generally work, it will most likely trigger an error as it will try to store the file upload array in the database instead of flat data.
那里有一些插件可以处理文件上传,将其签出,还可以在stackoverflow上搜索并检查文档以获取有关如何在保存之前修改数据的示例。
There are plugins out there that can handle file uploads, check them out, also search here on stackoverflow and check the docs for examples on how to modify data before it is being saved.
对于初学者:
- http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
- http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
- https://github.com/josegonzalez/cakephp-up
- http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
- http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
- https://github.com/josegonzalez/cakephp-upload
这篇关于一次将数据保存在cakephp hasmany中,并且属于associate Association的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!