将数据保存在 cakephp 中,同时具有多个关联和所属关联

2024-02-27

我知道这个问题在这里被问了很多次,但我也尽力遵循所提供的解决方案。当我学习 cakephp 时,一些解决方案似乎很难在代码中实现。我正在使用 cakephp 2.5。

我想做的是创建一份附有一个或多个上传内容的问题报告。以下是我迄今为止所实施的一些内容:-

我有以下型号:

  • 候选人
  • 考生问题报告
  • 考生问题报告上传

有协会如下:

  • 候选人问题报告有很多候选人问题报告上传

  • 候选人有很多候选人问题报告

  • 候选人问题报告属于候选人

  • 候选人问题报告上传属于候选人问题报告

候选人.php

    <?php

    class Candidate extends AppModel {

        public $name = 'Candidate';
        public $hasMany = array(

            'CandidatesProblemReport' => array(
                'className' => 'CandidatesProblemReport',
                'foreignKey' => 'candidate_id'
            )

        );
    }

候选人问题报告.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;
        }
    }

创建.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,但是当我保存关联数据时,它再次保存主模型,创建第二个重复条目,但上传未保存。


通过关联保存数据

这是预期的行为,saveAssociated()并不意味着只保存关联记录,它也会保存主记录,所以你应该使用saveAssociated()只是,不需要手动设置外键等,CakePHP 会自动完成。

控制器

public function create() {
    // ...

    if ($this->request->is('post') && !empty($this->request->data)):

        $this->CandidatesProblemReport->create();

        if ($this->CandidatesProblemReport->saveAssociated($this->request->data)):
            // ...
        endif;

    endif;
}

注意你的别名

未创建上传记录的原因是您没有在表单/数据中使用正确的别名,您已将别名设置为Uploads,但在你的形式中你正在使用CandidatesProblemReportsUpload,因此 CakePHP 将忽略此数据。

Form

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 不处理开箱即用的文件上传数据,您必须事先准备好它,以便将其存储在磁盘上,并且模型存储文件的路径。

虽然上面的代码通常应该可以工作,但它很可能会触发错误,因为它会尝试将文件上传数组而不是平面数据存储在数据库中。

有一些插件可以处理文件上传,查看它们,也可以在 stackoverflow 上搜索并查看文档以获取有关如何在保存数据之前修改数据的示例。

对于初学者:

  • http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
  • http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
  • https://github.com/josegonzalez/cakephp-upload https://github.com/josegonzalez/cakephp-upload
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将数据保存在 cakephp 中,同时具有多个关联和所属关联 的相关文章

随机推荐

  • 如何使用其他 Angular 组件中的“templateref”?

    如何使用templateRef来自其他组件模板文件 I have BatmanComponent SpidermanComponent and a JokerComponent 其中一些具有相似的功能 因此我决定创建一个HumanCompo
  • Xamarin 自定义表视图标头

    我想在表视图部分标题的标题中添加一个按钮 即加号按钮 经过研究发现 要做到这一点 您必须创建一个自定义标题 我不知道该怎么做 如何在 xamarin 中为表视图部分创建自定义标头 我也使用 Xaml 和 C 请参阅这些博客文章 https
  • 使用自定义字体为警报对话框项目设置字体

    我正在这样创建一个警报对话框 AlertDialog Builder alertDialog new AlertDialog Builder view getContext alertDialog setCustomTitle null a
  • 使用 where 和 offset fetch 子句的简单选择在 Oracle 中不起作用

    我正在尝试选择行where条件并且需要分页 所以我添加了Fetch with offset 使其动态 子句 但随后它给出了此错误 ORA 00933 SQL 命令未正确结束 位置 414 我的查询 SELECT up NAME upozil
  • 是否可以使用ggplot2中的facet_grid()让annotation_logtics()仅出现在一个子图上?

    我使用以下代码在 ggplot2 中使用facet grid 创建一个包含三个子图的图 day lt c 5 Aug 5 Aug 5 Aug 10 Aug 10 Aug 10 Aug 17 Aug 17 Aug 17 Aug station
  • [myArray addObject:[[objcBlock copy] autorelease]] 在释放数组时崩溃

    我编写了一个类来声明性地描述 UIView 动画序列 我的方法采用动画块的可变参数并将它们放入数组中 所以在我的循环中我想这样做 animations addObject block copy autorelease I first cop
  • 正则表达式匹配回句点或字符串开头

    我想匹配一个单词 然后获取它之前的所有内容 直到第一次出现一个句点或字符串的开头 例如 给定此字符串并搜索单词 regex s Do not match this Or this Or this either I like regex It
  • Elasticsearch 不返回单数/复数匹配项

    我正在使用 elasticsearch 的 php 库来索引和查找我的网站中的文档 这是创建索引的代码 curl XPUT http localhost 9200 test d index numberOfShards 1 numberOf
  • 如何在 SVG 中导出 PNG

    我在导出包含 PNG 图像的 SVG 时遇到一些问题 我在用着D3JS和以下代码 mysvg append image attr width 299 attr height 168 attr xlink href image png var
  • Passport.js 支持ajax 吗?

    我想用passport js进行ajax登录 我有设置 Passport js 的常用代码 route app post api auth login passport authenticate local login successRed
  • 协议“Line”只能用作通用约束,因为它具有 Self 或关联类型要求

    我正在快速使用协议 我认为它类似于其他语言中的 界面 我正在测试它如何处理变量 协议对我来说相当新 因为我从未见过带有非静态变量的接口 我创建了一个车站协议 protocol Station var id String get set va
  • 如果没有 .cs 文件,Web 应用程序将无法发布

    我有一个 asp net Web 应用程序项目 正在通过 Visual Studio 2013 中的 生成 gt 发布 来发布 我正在使用所选的预编译选项发布到文件系统 我的项目在打包 发布 Web 设置屏幕中选择了 仅运行此应用程序所需的
  • @Id 注解属性的 Kotlin 内联类

    在我的业务逻辑中 我必须处理很多实体 ID 所有这些 ID 都是类型String 这可能会导致混乱 尤其是当您将其中几个作为方法参数传递时 所以我考虑引入一点类型安全内联类 我知道 内联类在 v1 3 中仍然被标记为实验性的 然而 有没有人
  • 方向改变后的回调变为null

    我有一个FragmentActivity有两个选项卡 分别是ListFragments Each ListFragment有回调 回调的示例 回调在内部关联附加 method OnStatusUpdateListener mStatusUp
  • 删除阿拉伯语中的垃圾字符

    我需要从字符串中删除所有非阿拉伯字符 最终在堆栈溢出人员的帮助下 https stackoverflow com questions 6642341 remove garbage characters in utf 6643116 6643
  • 与 eclipse 项目相比,可运行 jar 运行速度太慢

    我从 eclipse 项目中提取了一个 jar 文件 但它运行速度太慢 大约需要二十分钟才能完成 而 eclipse 项目只需要几秒钟 我使用所有三种不同的选择导出了带有库处理的可运行 jar 我还导出了包含所有库处理选项的 jar 文件
  • 如何在 Yarn 上配置应用程序驱动程序自动重启

    来自 Spark 编程指南 要自动从驱动程序故障中恢复 用于运行流应用程序的部署基础架构必须监视驱动程序进程 并在驱动程序失败时重新启动驱动程序 不同的集群管理器有不同的工具来实现这一点 火花独立 火花独立 Spark应用程序驱动程序可以提
  • 无法创建迁移以将新列添加到表中:列名称无效

    我正在尝试向现有表添加一列 它只是一个字符串列 不涉及任何类型的键 这是我试图做的唯一更改 我正在使用 powershell 调用创建迁移 dotnet ef migrations add migration name context co
  • 我们如何在 TOMCAT 中生成堆栈跟踪?

    我们如何在 TOMCAT 中生成堆栈跟踪 我真正的问题是 TOMCAT 在执行某些库中定义的函数调用后停止 使用堆栈跟踪进行调试会很容易 您可以做很多事情 我假设下面您正在谈论 Java 堆栈跟踪 在Linux中 您可以通过执行kill 3
  • 将数据保存在 cakephp 中,同时具有多个关联和所属关联

    我知道这个问题在这里被问了很多次 但我也尽力遵循所提供的解决方案 当我学习 cakephp 时 一些解决方案似乎很难在代码中实现 我正在使用 cakephp 2 5 我想做的是创建一份附有一个或多个上传内容的问题报告 以下是我迄今为止所实施