Home > Backend Development > PHP Tutorial > ThinkPHP 转换数据库查询出的数据到对应类型

ThinkPHP 转换数据库查询出的数据到对应类型

WBOY
Release: 2016-06-20 12:32:03
Original
1100 people have browsed it

默认情况下,Thinkphp查询出的所有字段值类型都是String,如果是开发web,当然没问题,但开发接口,就很麻烦了,总不能让客户端去转类型。

ThinkPHP的Model.class.php时,提供了_parseType方法,可以在查询完以后,做类型转换,但框架没有这么干,需要我们手工调一下。

写一个Model基类:

BaseModel.class.php,因为我用到关联查询,所以继承自RelationModel

use Think\Model;use Think\Model\RelationModel;class BaseModel extends RelationModel{    //在查询后,转换数据类型    protected function _after_select(&$resultSet, $options)    {        parent::_after_select($resultSet,$options);        foreach ($resultSet as &$result) {            $this->_after_find($result, $options);        }    }    protected function _after_find(&$result, $options)    {        parent::_after_find($result,$options);        foreach ($result as $field => $value) {            $this->_parseType($result, $field);        }    }}
Copy after login

所有的Model类继承自BaseModel.

本来,这样已经搞定了,但发现Model.class.php的_parseType方法里有个低级bug,看图:

© 2016, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接!应用开发笔记

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template