【问题标题】:MapReduce not working in CakePHP 3.xMapReduce 在 CakePHP 3.x 中不起作用
【发布时间】:2016-02-12 07:40:59
【问题描述】:

我正在使用 CakePHP 3.x,我的应用程序有添加/编辑页面,在编辑操作中我正在使用此代码。

 $patient = $this->Patients->get($patientId);

获取患者记录。

现在我想在查找操作后修改某些字段的值,假设我想将 dob 字段(date_of_birth)转换为不同的日期格式,在 CakePHP 2.x 中可以在 afterFind 回调中但在 CakePHP 3 .x here 在最后一段中声明,

如果您需要在获取结果后修改结果,您应该使用Modifying Results with Map/Reduce 函数来修改结果。 map reduce 功能取代了之前版本的 CakePHP 中的“afterFind”回调。

我也使用过MapReduce,但它对我不起作用。

【问题讨论】:

  • 不起作用”不是正确的问题描述。请更具体地说明您的尝试究竟出了什么问题。

标签: php cakephp mapreduce cakephp-3.x


【解决方案1】:

Map/reduce 对于这样一个简单的任务来说有点过头了,我建议改用结果格式化程序,即Query::formatResults()

为了使用其中的任何一个,即映射器/缩减器或格式化程序,您必须使用Table::find() 而不是Table::get(),因为后者不会返回查询,但会返回结果和选项不支持映射器/缩减器或格式化程序。

但是,根据您需要格式化值的位置,帮助器、虚拟字段或仅在必要时进行格式化可能是更好的选择。

无论如何,这是一个基本的例子:

$patient = $this->Patients
    ->find();
    ->where([
        'id' => $patientId
    ])
    ->formatResults(function($results) {
        /* @var $results \Cake\Datasource\ResultSetInterface|\Cake\Collection\CollectionInterface */
        return $results->map(function($row) {
            // note that now `dob` is a string!
            $row['dob'] = $row['dob']->i18nFormat('dd. MMMM yyyy');
            return $row;
        });
    })
    ->firstOrFail();

另见

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多