PHP PDO lastInsertId 返回字符串而不是整数
我目前正在构建一个 symfony/doctrine 应用程序,一个模型具有以下结构:
Session:
columns:
session_id:
type: integer(8)
primary: true
autoincrement: true
session_number:
type: string(30)
这正确映射到数据库为:
CREATE TABLE `session` (
`session_id` bigint(20) NOT NULL AUTO_INCREMENT,
`session_number` varchar(30) NOT NULL,
所以我们在那里是安全的。
然后,当尝试创建新记录时,代码会这样:
$newSession = new Session();
$newSession->session_number = session_id();
$newSession->save();
//...
echo $newSession->session_id; //<------ this will return a string '1'
最后一行是有问题的。 session_id字段被填充为最后一个身份值,但是作为字符串!!
所以一开始我认为教义是罪魁祸首,但是后来调试代码,我发现似乎PDO是实际上是将值作为字符串返回的。被调用的方法是:
dbh->lastInsertId()
所以明显的问题是:我该如何解决这个问题?。我在互联网上找到了这些东西,但还没有尝试过:
- PDO::ATTR_STRINGIFY_FETCHES。这行得通吗?如果是,我该如何配置?
- 使用 mysql 本机驱动程序而不是 pdo。然而,教义处理它,所以我不确定我是否可以配置它。
- 另一个明显的解决方法是类型转换为 int : (int)$session->session_id。但这实在是丑陋,因为它应该返回一个整数值(这就是使用 pdo 和学说的全部目的!)并且所有其他模型都会有同样的问题。
- 对此最好的解决方案是什么?
I'm currently building a symfony/doctrine app and one model has the following structure:
Session:
columns:
session_id:
type: integer(8)
primary: true
autoincrement: true
session_number:
type: string(30)
This correctly maps to the database as:
CREATE TABLE `session` (
`session_id` bigint(20) NOT NULL AUTO_INCREMENT,
`session_number` varchar(30) NOT NULL,
So we are safe there.
Then when trying to create a new record the code goes:
$newSession = new Session();
$newSession->session_number = session_id();
$newSession->save();
//...
echo $newSession->session_id; //<------ this will return a string '1'
The last line is the problematic. The session_id field gets filled in with the last identity value but as a string!!
So at first, I thought doctrine was the culprit, but then debugging the code, I found out that it seems that PDO is actually the one that is returning the value as a string. The method that gets called is:
dbh->lastInsertId()
So the obvious question is: how can I solve this?. I found these things in the internet but haven't tried them yet:
- PDO::ATTR_STRINGIFY_FETCHES. Will this work? If yes, how can I configure that?
- Using mysql native driver instead of pdo. However doctrine handles it so I'm not sure if I can even configure that.
- The other obvious workaround is to typecast to int : (int)$session->session_id. But that's just plain ugly as it should return an integer value (that's the whole purpose of using pdo and doctrine!) and all the other models would have the same issue.
- What would be the best solution for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想使用转换函数参见php手册。
为了在字符串表示的数字太大而无法转换为整数时发送异常(并避免代码中出现一些令人讨厌的间歇性错误),请用以下代码括起来:
You may want to use conversion function see php manual.
In order to send an exception if the string represents a too high number to be converted into an integer (and avoid some nasty intermittent bugs in your code), please surround with this code :