Laravel Enloquent发现返回null [英] Laravel Eloquent find returning null
问题描述
我试图通过使用Eloquents find方法从我的数据库中检索一条记录,但是它意外地返回null。如果我在数据库上手动运行查询,那么它返回预期的记录。
I'm trying to retrieve a record from my database using Eloquents find method, however, it's unexpectedly returning null. If I run the query manually on the database then it returns the expected record.
我在Laravel中使用以下内容:
I'm using the following in Laravel:
$support = Support::find(02155);
以下直接在数据库中:
SELECT * FROM support WHERE id = 02155;
主键列命名为id,类型为smallint(5),unsigned和zerofill自动增量设置。我根据Laravel应该执行的Laravel文档对上述手动查询进行了基础。
The primary key column is named 'id' with type smallint(5), unsigned and zerofill along with auto increment set. I based the above 'manual' query on the Laravel documentation according to what Laravel should be executing.
没有报告任何错误(我可以看到),如果我将Eloquent方法改为'all',所有记录都被正确地返回。
There aren't any errors reported (that I can see) and if I alter Eloquent method to 'all' then all of the records are correctly returned.
推荐答案
按照以下方式被PHP视为八进制: http://php.net/manual/en/language。 types.integer.php
This is caused because numbers starting with 0 are considered an octal by PHP, as per: http://php.net/manual/en/language.types.integer.php
在执行MySQL查询之前,PHP似乎将数字转换为十进制,这意味着查询的格式不正确。
It seems that PHP converts the number to a decimal before executing the MySQL query which means the query is formed with an incorrect number.
例如:
Support::find(02155);
成为:
'SELECT * FROM mytable WHERE id = 1133'
解决方案
我通过使用(int)类型转换为整数,在使用它与Enloquents find方法之前解决了这个问题。如果你将数字作为一个字符串(即引号)传递,也可以这样工作:
The Solution
I resolved this by typecasting the number to an integer using (int) before I used it with Eloquents find method. It will also work if you pass the number as a string (i.e. in quotes), like so:
Support::find('02155');
这篇关于Laravel Enloquent发现返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!