英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论