cakehp:使用save方法,我想在数据没有变化的情况下更新修改后的时间



请帮我解决这个问题,非常感谢。

第1部分:数据被更改,我使用[$this->abcModel->save($abc);],abcTable's修改的列被更改。===>正常。

第二部分:数据没有改变,我也希望abcTable's修改的列被改变,如何处理?(如果给我举个例子,会更好地理解。(

使用版本:cakehp3.3

Cakephp版本:cakehp3.3

$this->Model->touch($data);

[Rf.]https://book.cakephp.org/3.0/en/orm/behaviors/timestamp.html

让我们假设您有一个包含以下字段的表单。

Name: XYZ 
Number :077777777
**save** button.

它具有表单操作编辑/更新

情况1:用户进行更改并保存表单。情况2:用户不进行任何更改并保存表单。

在任何一种情况下,都应该调用控制器的编辑(或更新(函数。您的姓名和号码字段将在控制器中可用,可以通过$this->request->getData((方法。理想情况下,时间戳需要两个字段,如下所示:"CREATED_ON"one_answers"UPDATED_ON">

您可以使用您提到的触摸方法,但在理想的情况下,最好将行为写入您的模型。每次创建新记录或更改/保存记录时,它都会更新时间戳。

<?php
namespace AppModelBehavior;
use CakeORMBehaviorTimestampBehavior;
/**
 * Modify built in CakePHP's Timestamp class's default config so no configuration is necessary for use in this project.
 */
final class CustomTimestampBehavior extends TimestampBehavior
{
    /**
     * Default config
     *
     * These are merged with user-provided config when the behavior is used.
     *
     * events - an event-name keyed array of which fields to update, and when, for a given event
     * possible values for when a field will be updated are "always", "new" or "existing", to set
     * the field value always, only when a new record or only when an existing record.
     *
     * refreshTimestamp - if true (the default) the timestamp used will be the current time when
     * the code is executed, to set to an explicit date time value - set refreshTimetamp to false
     * and call setTimestamp() on the behavior class before use.
     *
     * @var array
     */
    protected $_defaultConfig = [
        'implementedFinders' => [],
        'implementedMethods' => [
            'timestamp' => 'timestamp',
            'touch' => 'touch',
        ],
        'events' => [
            'Model.beforeSave' => [
                'CREATED_ON' => 'new',
                'UPDATED_ON' => 'existing',
            ]
        ],
        'refreshTimestamp' => true
    ];
}

并从您的模型表中调用它。如下所示:

   public function initialize(array $config)
    {
        parent::initialize($config);

        $this
            ->addBehavior('CustomTimestamp');

这样,您就不需要每次手动调用$This->model->touch($data(。无论何时创建或保存,行为都会处理它。

参考编号:https://api.cakephp.org/3.0/class-Cake.ORM.Behavior.TimestampBehavior.html

相关内容

最新更新