There is no problem not worth solving, and no technology not worth learning!

In Laravel 6, without changing the frame default timezone: Asia/Shanghai, the datetime format is adjusted to UTC (2)

在有需要使用到 UTC 的模型中,引入新的 trait 文件,查看未使用新的 trait 与使用了新的 trait 的区别。相差 8 小时

1. Since the time zone of the program body is: Asia/Shanghai, but in some models, the time zone value of UTC is planned to be stored

2. Reference:https://www.shuijingwanwq.com/2022/07/11/6776/, the findings are still not as expected. After adjustment in step 7. The same program, after running in the queue, the value of the field updated_at is sometimes still: Asia/Shanghai, and most of the time zone is: UTC. as shown in Figure 1

参考:https://www.shuijingwanwq.com/2022/07/11/6776/ ,发现仍然不符合预期。在第 7 步骤的调整后。同样的程序,在队列中运行后,字段 updated_at 的值,其对应的时区有时候仍然为:Asia/Shanghai,大部份时候的时区为:UTC
Figure 1

3. Temporarily adjusted to the following implementation, when $value is a string, the current UTC time is returned.


    /**
     * 转换时区
     *
     * @param $value
     * @return string
     */
    private function transTz($value = null): string
    {
        return now()->utc()->toDateTimeString();
    }


4. It is found that the time zone is still: Asia/Shanghai. However, it is found that the time zone is constantly changing, which may be caused by the constant save() in the queue. The save() method is executed more than 5 times in the same model in the queue. as shown in Figure 2

发现仍然存在时区为:Asia/Shanghai 的情况。不过发现时区在不断变换的模型,可能是因为在队列中不断地 save() 所导致。大概在队列中同一个模型执行了 5 次以上的 save() 方法
Figure 2

5. The final decision to adopt the plan that follows the original step 4. However, the scheme of step 4 does not apply to the delete() method, and the time zone of the value of deleted_at is still assia/shanghai in the SQL generated by it. as shown in Figure 3

最终决定采用沿用原有步骤 4 的方案。不过步骤 4 的方案不适用于 delete() 方法,其生成的 SQL 中,deleted_at 的值的时区仍然为:Asia/Shanghai
Figure 3

update `table` set `deleted_at` = '2023-01-12 11:19:17' where `id` = 534


6. Decide to still use the modifier, because it is in the same queue, the same model will only execute the delete() method once.


    /**
     * 设置删除时间
     *
     * @param $value
     * @return void
     */
    public function setDeletedAtAttribute($value)
    {
        $this->attributes['deleted_at'] = $value ? now()->utc()->toDateTimeString() : $value;
    }


7. The final SQL found that the generated SQL does not meet the expectations, and the time zone is still: Asia/Shanghai


update `table` set `deleted_at` = '2023-01-12 16:05:00' where `id` = 531


8. Try to overwrite the method: runsoftdelete() because soft delete uses trait softdeletes

Before editing:


$time = $this->freshTimestamp();


After editing:


$time = Date::now('UTC');


9. It is found that the generated sql meets the expectations, the time zone is: UTC


update `table` set `deleted_at` = '2023-01-12 08:09:02' where `id` = 534


10. In the model that needs to use the UTC timezone, the final implementation is as follows


use Illuminate\Database\Eloquent\SoftDeletes;

class ThemeInstallation extends Model
{
    use SoftDeletes;



    /**
     * Perform the actual delete query on this model instance.
     *
     * @return void
     */
    protected function runSoftDelete()
    {
        $query = $this->setKeysForSaveQuery($this->newModelQuery());

        $time = Date::now('UTC');

        $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];
        file_put_contents(storage_path() . '/logs/SoftDeletes.runSoftDelete-' . microtime(true) . '-' . mt_rand()  . '.txt', print_r($time, true), FILE_APPEND | LOCK_EX);

        $this->{$this->getDeletedAtColumn()} = $time;

        if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
            $this->{$this->getUpdatedAtColumn()} = $time;

            $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
        }

        $query->update($columns);

        $this->syncOriginalAttributes(array_keys($columns));
    }
}


11. Since there are multiple models that need to use UTC timezone, in order to avoid code redundancy, create a new trait file: /app/traits/utcsoftdeletes.php


setKeysForSaveQuery($this->newModelQuery());

        $time = Date::now('UTC');

        $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];

        $this->{$this->getDeletedAtColumn()} = $time;

        if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
            $this->{$this->getUpdatedAtColumn()} = $time;

            $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
        }

        $query->update($columns);

        $this->syncOriginalAttributes(array_keys($columns));
    }
}



12. In the model that needs to use UTC, introduce a new trait file to see the difference between the unused new trait and the new trait used. 8 hours apart. as shown in Figure 4

在有需要使用到 UTC 的模型中,引入新的 trait 文件,查看未使用新的 trait 与使用了新的 trait 的区别。相差 8 小时
Figure 4

PHP / Laravel / Yii2 Legacy Project Maintenance & Long-Term Technical Support

If your PHP / Laravel / Yii2 project is already in production but needs bug fixing, API troubleshooting, performance optimization, developer handover support, or long-term maintenance, feel free to contact me for remote technical support.

Ideal For:
✅ PHP legacy systems without active maintenance
✅ Laravel / Yii2 project bug fixes
✅ Admin panel feature iterations
✅ RESTful API troubleshooting
✅ MySQL / Redis / Nginx performance issues
✅ Long-term remote part-time maintenance

We can start with a small task:
✅ Production error troubleshooting
✅ API issue analysis
✅ Slow query and performance bottleneck diagnosis
✅ Initial code structure review
✅ Deployment environment and log inspection

If you would like to discuss your project, please contact me and mention: PHP Maintenance Consultation.

Contact Me:
Telegram: @shuijingwan
WeChat: 13980074657
Email: shuijingwanwq@gmail.com

评论

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.