这篇文章主要介绍了thinkphp实现转换数据库查询结果数据到对应类型的方法,涉及thinkphp模型类操作及针对源码文件的相关修改方法,需要的朋友可以参考下
本文实例讲述了thinkphp实现转换数据库查询结果数据到对应类型的方法。分享给大家供大家参考,具体如下:
最近使用 thinkphp3.2.3 进行 api 开发,发现 thinkphp3.x 查询数据库返回所有字段值类型都是 string。以前开发 web 的时候没怎么注意这个,现在发现用到 api 开发很难办,数据类型不对,不能每个字段都让客户端自己强制转换一下。
查资料后发现 thinkphp3.x 的 model.class.php,提供了 _parsetype 方法,在查询完以后进行类型转换,但需要我们手工调一下。
需要自己写一个 model 基类:
mbasemodel.class.php 继承自 model
use think\model;class basemodel extends model{ 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); } }}
然后所有自己写的 model 类都继承自 mbasemodel.
注意:必须把上面两个方法写到 model 的子类中。
本来,这样已经搞定了,但发现 model.class.php 的 _parsetype 方法里有个低级 bug:
/*** 数据类型检测* @access protected* @param mixed $data 数据* @param string $key 字段名* @return void*/protected function _parsetype(&$data,$key) { if(!isset($this->options['bind'][':'.$key]) && isset($this->fields['_type'][$key])){ $fieldtype = strtolower($this->fields['_type'][$key]); if(false !== strpos($fieldtype,'enum')){ // 支持enum类型优先检测 }elseif(false === strpos($fieldtype,'bigint') && false !== strpos($fieldtype,'int')) { $data[$key] = intval($data[$key]); }elseif(false !== strpos($fieldtype,'float') || false !== strpos($fieldtype,'double')){ $data[$key] = floatval($data[$key]); }elseif(false !== strpos($fieldtype,'bool')){ $data[$key] = (bool)$data[$key]; } }}// 上面第13行修改为}elseif(false !== strpos($fieldtype,'bigint') || false !== strpos($fieldtype,'int') || false !== strpos($fieldtype,'tinyint')) {
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
thinkphp数据库的增删改查操作
thinkphp5实现数据库添加内容的方法
thinkphp3.2.3版本的数据库增删改查实现代码
以上就是thinkphp实现转换数据库查询结果数据到对应类型的详细内容。