PHP sqlite返回所有字符串,无论定义了哪种数据类型 [英] PHP sqlite is returning all strings no matter what data type is defined
问题描述
我正在使用内存数据库中的sqlite运行单元测试,但遇到了问题.
I'm running unit tests using the sqlite in memory database and I've run into an issue.
当我使用mysql数据库执行测试时,以下比较正常工作
When I perform the tests using a mysql database, the following comparison works properly
if ($item->user_id === Auth::id())
如果数字匹配则为true,否则为false.当我在内存数据库中使用sqlite时,条件语句将始终返回false
,因为user_id
属性是作为string
而不是正确的int
数据类型返回的.
It will evaluate to true if the numbers match and false if they don't. When I use the sqlite in memory database the conditional statement will always return false
because the user_id
attribute is returned as a string
instead of the proper int
data type.
我已经阅读了几篇文章和评论,说这对于PHP中的sqlite是可配置的,而其他人则说它不能更改.我想使用内存sqlite数据库进行测试,但是如果无法更改此行为,则必须更改条件以使用==
而不是更严格的===
.如何更改sqlite查询的行为?
I've read a few posts and comments saying this is a configurable thing for sqlite in PHP and others saying it cannot be changed. I want to use the in memory sqlite database for my tests but if I can't change this behavior I have to change my conditionals to use ==
instead of the more strict ===
. How can I change the behavior of the sqlite queries?
更新
我还尝试将其添加到sqlite配置中
I've also tried adding this to the sqlite configuration
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'options' => [
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::FETCH_NUM => true,
],
],
这也无济于事.
推荐答案
问题实际上出在PDO ,而不是SQLite或Laravel,并且实际上发生在所有数据库中.您从MySQL获取int
的事实表明您正在使用
The problem is actually with PDO, rather than SQLite or Laravel specifically, and in fact happens with all databases. The fact that you are getting int
s from MySQL suggests you are using the mysqlnd
driver, which solves this for MySQL.
我采用的解决方案是在明确地投射字段我的模型:
The solution I went with was to explicitly cast fields in my model:
protected $casts = [
'user_id' => 'integer'
];
这篇关于PHP sqlite返回所有字符串,无论定义了哪种数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!