Laravel,其中“小于”查询未显示预期结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33803729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:43:21  来源:igfitidea点击:

Laravel where 'less than' query not showing expected results

phpmysqllaraveleloquent

提问by Chris Townsend

I am trying to make a database query where I search for all of the items which have a lower current level than low stock level. When running the query I am getting no results and I'm not sure why.

我正在尝试进行数据库查询,在其中搜索当前水平低于低库存水平的所有项目。运行查询时我没有得到任何结果,我不知道为什么。

This is my query

这是我的查询

public static function getLowStockItemsCache()
{
         dd(\DB::table('items')->where('current_level', '<', 'low_stock_level')->get());
    }

When I die and dump this I get an empty collection.

当我死了并转储这个时,我会得到一个空的集合。

In my database I have the following records

在我的数据库中,我有以下记录

enter image description here

在此处输入图片说明

Both of these fields at set at int(11)

这两个字段都设置为 int(11)

If I reverse the query I get all 13 records.

如果我反转查询,我会得到所有 13 条记录。

Am I missing something small, as it's confusing me greatly and should be simple.

我是否遗漏了一些小东西,因为它让我非常困惑并且应该很简单。

回答by Bogdan

The third parameter is the value parameter which means it will be escaped when building the query to avoid SQL injection. If you want to compare two columns, you have to specifically tell the Query Builder that that part of the query should not be processed, either by using whereRawto pass the raw SQL condition:

第三个参数是 value 参数,这意味着在构建查询时将对其进行转义以避免 SQL 注入。如果要比较两列,则必须通过使用whereRaw传递原始 SQL 条件来明确告诉查询生成器不应处理该部分查询:

\DB::table('items')->whereRaw('current_level < low_stock_level')->get());

Or by using DB::raw()for the value only, so it's not escaped:

或者DB::raw()仅用于该值,因此它不会被转义:

\DB::table('items')->where('current_level', '<', DB::raw('low_stock_level'))->get());

回答by Delino

Laravel use 3 step argument on the "where" clause,

Laravel 在“where”子句上使用 3 步参数,

Pair::where('1st','2nd','3rd')

by default the 2nd arg is normally default equal sign, saying the 1st arg is equal to the 3rd arg,

默认情况下,第二个参数通常是默认的等号,表示第一个参数等于第三个参数,

Pair::where('name', 'john')->get();

Pair::where('stock', '<', '100')->get();

When you find this logics then you understand the "where" tricks

当你找到这个逻辑时,你就会理解“哪里”的技巧