当你从模型中的数据库中检索数据时,将所有值都返回为字符串。
例如,如果您加载模型$ user = User :: findFirst(1),当您访问属性$ user-> id时,它返回一个(字符串)“1”。
我在模型中声明元数据以尝试获取php类型,但不起作用:
public function metaData()
{
return array(
//Every column in the mapped table
MetaData::MODELS_ATTRIBUTES => array(
'id', 'email', 'password', 'created'
),
//Every column part of the primary key
MetaData::MODELS_PRIMARY_KEY => array(
'id'
),
//Every column that isn't part of the primary key
MetaData::MODELS_NON_PRIMARY_KEY => array(
'email', 'password', 'created'
),
//Every column that doesn't allows null values
MetaData::MODELS_NOT_NULL => array(
'id', 'email', 'password', 'created'
),
//Every column and their data types
MetaData::MODELS_DATA_TYPES => array(
'id' => Column::TYPE_INTEGER,
'email' => Column::TYPE_VARCHAR,
'password' => Column::TYPE_VARCHAR,
'created' => Column::TYPE_INTEGER,
),
//The columns that have numeric data types
MetaData::MODELS_DATA_TYPES_NUMERIC => array(
'id' => true,
'year' => true,
),
//The identity column, use boolean false if the model doesn't have
//an identity column
MetaData::MODELS_IDENTITY_COLUMN => 'id',
//How every column must be bound/casted
MetaData::MODELS_DATA_TYPES_BIND => array(
'id' => Column::BIND_PARAM_INT,
'email' => Column::BIND_PARAM_STR,
'password' => Column::BIND_PARAM_STR,
'created' => Column::BIND_PARAM_INT,
),
//Fields that must be ignored from INSERT SQL statements
MetaData::MODELS_AUTOMATIC_DEFAULT_INSERT => array(
'id' => true
),
);
}
Phalcon有办法将sql类型自动转换为php类型吗? 感谢。
答案 0 :(得分:2)
如果您使用Phalcon \ Db \ Adapter \ Pdo \ Mysql作为适配器,默认情况下整数将作为字符串在PDO中返回
返回正确的类型,您需要为适配器设置适当的选项,
你需要设置
ATTR_EMULATE_PREPARES
和ATTR_STRINGIFY_FETCHES
到false
您需要在配置或服务文件中更改您的适配器代码,如此设置
return new Phalcon\Db\Adapter\Pdo\Mysql([
'host' => 'DATABASE_HOST',
'username' => 'USERNAME',
'password' => 'PASSWORD',
'dbname' => 'DATABASE_NAME',
'options' => array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_STRINGIFY_FETCHES => false,
)
]);
答案 1 :(得分:0)
重要的是要说你需要原生的mysql驱动程序。否则选项不会影响。
sudo apt-get purge php5-mysql
sudo apt-get install php5-mysqlnd