think-orm icon indicating copy to clipboard operation
think-orm copied to clipboard

ThinkORM4有没有办法关闭所有模型字段的自动转换?

Open HeroTianTYJ opened this issue 8 months ago • 2 comments

我知道可以在模型类中设置type成员字段,但是这样只能一个字段一个字段的关闭,我们有十几个项目,几百个模型类,超多字段,在之前都手动转换好了,升级到4.0,有些字段就显示不正常了

HeroTianTYJ avatar May 14 '25 03:05 HeroTianTYJ

你举例说明下,什么场景下不需要自动转换

liu21st avatar May 14 '25 06:05 liu21st

我猜是 在旧版本或是 禁用了 NO_ZERO_DATEMySQL版本中, datetime/date 类型支持值为 0000-00-00 00:00:00 或 0000-00-00.

表现为: 强制转换后, 值会变成 -0001-11-30 00:00:00 或 -0001-11-30 .

原因: date('Y-m-d H:i:s', strtotime('0000-00-00 00:00:00'))

文档中也提到过这个问题: https://www.php.net/manual/zh/datetime.formats.php

解决方法, 提供个思路

class NewModel extends Model
{
    public function toArray(): array
    {
        return array_map(function ($value) {
            if ($value === '-0001-11-30 00:00:00') {
                return '0000-00-00 00:00:00';
            }
            return $value;
        }, parent::toArray());
    }
    public function __get(string $name)
    {
        $value = $this->get($name);
        if ($value === '-0001-11-30 00:00:00') {
            return '0000-00-00 00:00:00';
        }
        return $value;
    }
}

ghostong avatar Sep 24 '25 10:09 ghostong