CodeIgniter 活动记录返回 Mysql 数据类型而不仅仅是字符串

3

我是使用CodeIgniter 2.0.3版本的。我想知道是否有一种简单的方法来返回正确数据类型的数据。例如,对于模式:

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| term  | varchar(255) | NO   |     | NULL    |                |
| level | int(11)      | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

Active Record result_array 返回:

array(4) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["term"]=>
    string(11) "Mesoamerica"
    ["level"]=>
    string(1) "1"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(1) "2"
    ["term"]=>
    string(6) "Mexico"
    ["level"]=>
    string(1) "1"
  }
  [2]=>
  array(3) {
    ["id"]=>
    string(1) "3"
    ["term"]=>
    string(10) "indigenous"
    ["level"]=>
    string(1) "2"
  }
  [3]=>
  array(3) {
    ["id"]=>
    string(1) "4"
    ["term"]=>
    string(5) "ruins"
    ["level"]=>
    string(1) "2"
  }
}

这个想法是让类型在结果集中显示出来。 ID 应该是 INTEGER,而 level 应该是 INTEGER。 我通常会将需要使用的数据进行强制类型转换。但在 CodeIgniter 文档中似乎没有找到任何推动这一点的方式,希望能有简便的方法来完成。我看到了 PDO 中实现这一点的方法,但是 CodeIgniter 中是否提供类似方便的实现呢?

如果您使用result()而不是result_array(),则会返回一个对象。 - Ayush
@xbonez 我刚试了一下,以为我可能漏掉了什么,但它仍然将所有内容返回为字符串。 - dm03514
3
请点击此处阅读:http://codeigniter.com/forums/viewthread/110393/ - Yan Berk
@YanBerk,你的链接似乎已经失效了,这是新的网址:http://forum.codeigniter.com/archive/index.php?thread-17289.html。 - vincentp
2个回答

2

这是我做的一个辅助工具:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * cast_fields
 *
 * Casts string values provided from database into
 * the appropriate datatype of possible.
 */
if ( ! function_exists('cast_fields'))
{
    function cast_fields($fields, $results)
    {
        for($i=0; $i<count($fields); $i++) {
            $name = $fields[ $i ]->name;
            $type = $fields[ $i ]->type;
            $int_types = array(
                'int',
                'tinyint',
                'smallint',
                'mediumint',
                'bigint'
            );
            if(in_array($type, $int_types)) {
                for($j=0; $j<count($results); $j++) {
                    $casted = intval( $results[ $j ]->{ $name } );
                    $results[ $j ]->{ $name } = $casted;
                }
            }
        }
        return $results;
    }

}

/* End of file field_data_helper.php */
/* Location: ./application/helpers/field_data_helper.php */

目前它仅适用于整数。您可以扩展它以支持其他数据类型。
如何使用它:
// Get rows from database.
$query = $this->db->get_where( $this->table, $criteria, $limit, $offset );
$results = $query->result();

// Cast data to the correct datatypes.
$fields = $this->db->field_data( $this->table );
$this->load->helper('field_data_helper');
$results = cast_fields($fields, $results);

这是一个很好的解决方案,直到你使用连接操作时 :( - RedactedProfile

0
我采取了不幸的方法:我只是更改了/system/database/DB_Result.php文件。
custom_result_object方法中,第85行看起来像这样:
$object->$key = $value; 

将其更改为:

if(is_numeric($value)) $object->$key = (int)$value;
else $object->$key = $value;

然后在任何地方添加此方法:

/**
* Scans a rowset to cast valid ints as integers instead of strings
*/
private function recast($row)
{
    foreach($row as $key => $value)
    {
        if(is_object($row)) {
            if(is_numeric($value)) $row->{$key} = (int)$value;
        } else {
            if(is_numeric($value)) $row[$key] = (int)$value;
        }

    }

    return $row;
} 

然后在result_object()中查找

$this->result_object[] = $row;

在那行的上方添加

$row = $this->recast($row);

然后在 result_array() 中查找

$this->result_array[] = $row;

在那行的上方添加

$row = $this->recast($row);

然后在 custom_row_object() 函数中找到

$this->current_row = $n;

在那行之上,添加

$n = $this->recast($n);

然后在row_object()中查找

$this->current_row = $n;

在那行的上方添加

$n = $this->recast($n);

然后在row_array()中查找

$this->current_row = $n;

在那行的上方添加

$n = $this->recast($n);

当然,recast函数可以根据您的解析需求进行修改和更新,现在它只是将整数转换而不使用正则表达式。这种方法使日期时间戳保持不变,但任何应该是数字值的东西都会被解析。

还可以进行一些额外的浮点数检查等操作。

我只需要为API函数执行此操作,因为json_encode将所有整数强制转换为字符串,id:"1"而不是id:1,需要一个能够反映整个站点的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接