ThinkPHP Realizes the Method of Transforming Database Query Result Data to Corresponding Types
- 2021-08-21 19:48:43
- OfStack
In this paper, an example of ThinkPHP to achieve the transformation of database query results data to the corresponding type of method. Share it for your reference, as follows:
Recent API development using ThinkPHP3.2. 3 found that the ThinkPHP3.x query database returned all field value types of String. I didn't pay much attention to this when I developed web before, but now I find it difficult to develop API, and the data type is wrong, so I can't let the client cast 1 field by myself.
After checking the data, it is found that Model. class. php of ThinkPHP3.x provides the _ parseType method, and the type conversion is carried out after the query, but we need to manually adjust 1.
You need to write your own Model base class:
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 Model classes written by yourself inherit from MBaseModel.
Note: The above two methods must be written to the subclass of Model.
Originally, this was done, but it was found that there was a low-level bug in the _ parseType method of Model. class. php:
/**
* 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];
}
}
}
// Above 13 Row is modified to read
}elseif(false !== strpos($fieldType,'bigint') || false !== strpos($fieldType,'int') || false !== strpos($fieldType,'tinyint')) {
For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".
I hope this article is helpful to the PHP programming based on ThinkPHP framework.