Laravel-雄辩地在比较之前将查询参数转换为整数 [英] Laravel - Eloquent converts query parameter to integer before comparison
问题描述
我试图基于主键从表中返回一行.
I'm trying to return a single row from a table based on the primary key.
$product = Product::where('id', '=', $idOrSKU)
->orWhere('sku', '=', $idOrSKU)
->take(1)->get();
由于某种原因,$idorSKU
在进行比较之前被转换为和(int)
.例如,当$isOrSKU = "9dfghfd"
时,返回ID = 9的行.为什么是这样?它应该什么也不返回!有人可以解释吗?
For some reason $idorSKU
is being converted to and (int)
before the comparison happens. For example, when $isOrSKU = "9dfghfd"
, the row with ID=9 is returned. Why is this? It should return nothing at all! Can someone explain this?
这是相关的餐桌计划
| id | int(10) unsigned | NO | PRI | NULL
| name | varchar(255) | NO | | NULL
| sku | varchar(255) | NO | | NULL
推荐答案
这与数据库(而不是Laravel)有关,是对字符串的类型转换.因为您正在对int(10)
列进行查询,所以mySQL强制将搜索字符串更改为int
,从而使查询变为9
.
This is related to the database, not Laravel, typecasting your string. Because you are doing a query on an int(10)
column, mySQL is forcably changing your search string to an int
, causing your query to become 9
.
我可以确认以下内容:
$test1 = Test::find('1');
echo $test1->id; // gives 1
$test2 = Test::find('1example');
echo $test2->id; // gives 1
因此您的变量9dfghfd
是因为类型转换为int (9)
.但是,如果您的变量是"df9ghfd",则不会进行类型转换,也不会匹配.
Therefore your variable of 9dfghfd
because typecast to int (9)
. But if your variable was "df9ghfd" - it would not be typecast, and it wont match.
该问题会影响其他因素,例如路由模型绑定:
The issue affects other things, like Route model binding:
domain.com/product/1
domain.com/product/1thisalsoworks // takes you to the page of ID 1
我已经在Github上打开了一张票,以进行进一步的讨论-请在此处查看以获得更多信息/讨论.
I've opened a ticket on Github to discuss it further - so check here for further information/discussion.
但是总的来说,这不是Laravel的直接过错.
But overall the issue is not a direct fault of Laravel.
似乎该问题影响了GitHub 本身:
seems the issue affects GitHub itself:
这有效: https://github.com/laravel/framework/issues/5254
这样做也是这样: https://github.com/laravel/framework/issues/5254typecast
这篇关于Laravel-雄辩地在比较之前将查询参数转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!