Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

database配置auto_timestamp和datetime_field不生效 #2921

Open
firezihai opened this issue Aug 2, 2023 · 2 comments
Open

database配置auto_timestamp和datetime_field不生效 #2921

firezihai opened this issue Aug 2, 2023 · 2 comments

Comments

@firezihai
Copy link

firezihai commented Aug 2, 2023

database文件配置

'auto_timestamp'  => true,

    // 时间字段取出后的默认时间格式
    'datetime_format' => 'Y-m-d H:i:s',

    // 时间字段配置 配置格式:create_time,update_time
    'datetime_field'  => 'created_at,updated_at',

模型文件必需配置$createTime、$updateTime或者$autoWriteTimestamp,或者将ModelService设置autoWriteTimestamp的代码调至设置时间字段代码的后面,就能生效。
不生效

class Model extends \think\Model
{
}

生效

class Model extends \think\Model
{
      protected $autoWriteTimestamp = true;
}

生效

class Model extends \think\Model
{
     protected $createTime = 'created_at';
     protected $updateTime = 'updated_at';
}

生效

class ModelService extends Service
{
    public function boot()
    {
		//
        Model::setDb($this->app->db);
        Model::setEvent($this->app->event);
        Model::setInvoker([$this->app, 'invoke']);
        Model::maker(function (Model $model) {
            $config = $this->app->config;

           

            $dateFormat = $model->getDateFormat();

            if (is_null($dateFormat)) {
                // 设置时间戳格式
                $model->setDateFormat($config->get('database.datetime_format', 'Y-m-d H:i:s'));
            }

            $timeField = $config->get('database.datetime_field');
            if (!empty($timeField)) {
                [$createTime, $updateTime] = explode(',', $timeField);
                $model->setTimeField($createTime, $updateTime);
            }
	
	    $isAutoWriteTimestamp = $model->getAutoWriteTimestamp();

            if (is_null($isAutoWriteTimestamp)) {
                // 自动写入时间戳
                $model->isAutoWriteTimestamp($config->get('database.auto_timestamp', 'timestamp'));
            }
        });
    }
}

这个是bug,还设计就是如此?如果设计如此,那不是每个模型都必须设置autoWriteTimestamp属性?

@dongwlin
Copy link

dongwlin commented Aug 2, 2023

可以整个BaseModel,然后继承BaseModel

@firezihai
Copy link
Author

可以整个BaseModel,然后继承BaseModel

真不知道这是不是bug,如果要实现也只能这样新建一个基类了。只是thinkphp这种设计让人不容易发现问题所在

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants