【问题标题】:cakephp: Use save method , I want to update modified time when data no changedcakephp:使用保存方法,我想在数据没有变化时更新修改时间
【发布时间】:2024-01-12 14:33:01
【问题描述】:

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

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

第 2 部分:数据没有改变,我也想要 abcTable's 修改的列被改变, 怎么办? (如果给我一个例子,会更好理解。)

使用版本:cakephp 3.3

【问题讨论】:

标签: cakephp time save


【解决方案1】:

Cakephp 版本:cakephp 3.3

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

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

【讨论】:

    【解决方案2】:

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

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

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

    案例 1: 用户进行更改并保存表单。 案例 2: 用户不做任何更改并保存表单。

    在任何一种情况下,您都应该调用控制器的编辑(或更新)函数。 您的 NAME AND NUMBER 字段将在您的控制器中可用,并且可以通过以下方式访问 $this->request->getData() 方法。 理想情况下,您需要两个时间戳字段,如下所示: 'CREATED_ON' 和 'UPDATED_ON'

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

    <?php
    namespace App\Model\Behavior;
    
    use Cake\ORM\Behavior\TimestampBehavior;
    
    /**
     * 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

    【讨论】: