CakePHP 4 查询:我不需要 created_at 作为 FrozenTime,字符串就足够

huangapple go评论52阅读模式
英文:

CakePHP 4 Query: I don't need created_at as FrozenTime, string is enough

问题

有时,当我从数据库获取数据时,我希望数据以数组的形式返回 - 方法disableHydration()可以实现这一点。但是数据库中的时间戳字段仍然以FrozenTime对象的形式返回。

是否可以(以及如何)在我不需要时关闭自动将时间戳字段替换为FrozenTime类型对象的功能?

以下代码返回:
(...)
'created_at' => object(Cake\I18n\FrozenTime) id:0 { },
'updated_at' => object(Cake\I18n\FrozenTime) id:0 { },
(...)

对我来说,下面这样就足够了:
'created_at' => (string) '2023-01-01 12:00:00',
'updated_at' => (string) '2023-02-02 12:00:00',

英文:

Sometimes when I get data from database, i want data as array - method disableHydration() does it.
But timestamp fields (in the database) are still returned as objects FrozenTime.

Is it possible (and how) to turn off the automatic replacement of timestamp fields with objects of the type FrozenTime, when i don't need it?

$query->find()->disableHydration()->first();

returns:
(...)
'created_at' => object(Cake\I18n\FrozenTime) id:0 { },
'updated_at' => object(Cake\I18n\FrozenTime) id:0 { },
(...)

It would be enough for me:
'created_at' => (string) '2023-01-01 12:00:00',
'updated_at' => (string) '2023-02-02 12:00:00',

答案1

得分: 1

你好,根据所需的表,即/src/Model/Table || /Entity,在你的表/实体PHP文件中,在initialize函数下插入以下内容:

$this->getSchema()->setColumnType('created_at', 'string');

这应该有助于解决此问题。到目前为止,这是我在浏览源文件后找到的唯一方法。我必须这样做,以便为我的项目创建所需的JSON对象,而不创建for/foreach循环并重建我的嵌套/InnerJoin模型。

英文:

Hello under the required table i.e. /src/Model/Table || /Entity , open your table / entity php file and under initialize function insert

$this->getSchema()->setColumnType('created_at', 'string');

That should help resolve this. so far this was the only way I could find after going thru the source files. I had to do this in other to create the needed JSON Objects for my project, without creating a for/foreach loops and rebuilding my nested / InnerJoin Models.

huangapple
  • 本文由 发表于 2023年5月31日 22:39:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76374678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定