Laravel Eloquent find returning null

你。 提交于 2019-12-23 12:11:20

问题


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.

I'm using the following in Laravel:

$support = Support::find(02155);

And the following directly on the database:

SELECT * FROM support WHERE id = 02155;

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.

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.


回答1:


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

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.

For example:

Support::find(02155);

Becomes:

'SELECT * FROM mytable WHERE id = 1133'

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');


来源:https://stackoverflow.com/questions/15326140/laravel-eloquent-find-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!