This article mainly introduces the thinkphp implementation of the conversion database query results data to the corresponding type of method, involving the Thinkphp model class operation and related to the source file modification method, the need for friends can refer to the next
In this paper, we describe the method of thinkphp implementing transforming database query result data to corresponding type. Share to everyone for your reference, as follows:
Recently, using ThinkPHP3.2.3 for API development, we found that the thinkphp3.x query database returned all field value types as String. The previous development of the web did not pay much attention to this, now found that the use of API development is difficult to do, the data type is not correct, not every field to let the client self-cast.
After checking the data found thinkphp3.x Model.class.php, provided a _parsetype method, after the query after the type conversion, but we need to manually adjust.
You need to write a Model base class yourself:
MBaseModel.class.php inherits from 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);}}
Then all of the Model classes that you write are inherited from Mbasemodel.
Note: The above two methods must be written to a subclass of Model.
Originally, this has been done, but found Model.class.php _parsetype Method has a low-level bug:
/*** Data Type detection * @access protected* @param mixed $data data * @param string $key field name * @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 ')) { //support enum type First detection }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]; } } The 13th line above is modified to}elseif (False!== Strpos ($fieldType, ' bigint ') | | false!== strpos ($fieldType, ' int ') | | false!== strpos ($fiel DType, ' tinyint ')) {
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!