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    |                |
+-------+--------------+------+-----+---------+----------------+

アクティブレコードは以下を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はこれを行うための何らかの便利さを提供しますか?

4

2 に答える 2

1

これが私が作ったヘルパーです:

<?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);
于 2014-06-21T20:37:52.350 に答える