首页 > 解决方案 > Laravel 查询获取错误数据

问题描述

我写了 Laravel 搜索查询。

$product = Product::where('user_role_id', '=', 3)
                           ->where('user_id', '!=', $user_id)
                           ->where('quantity_in_stock', '>', 0);
                if (!empty($suggestion)) {
                    $product->where('product_name', 'like', '%' . $suggestion . '%')->orWhere('ndc_number', 'like', '%' . $suggestion . '%');
                }
                $search = $product->orderby('id', 'desc')->get();
                $products = $search->toArray();

但我的问题是,当我查看搜索结果时,我发现了这样的结果,user_role_id => 2但在查询中我给出的结果等于 3。

可以帮助解决这个问题。

谢谢

标签: mysqllaravel-5eloquent

解决方案


那是因为您的查询被翻译为:

SELECT * 
FROM products
WHERE user_role_id = 1 
AND user_id != ? 
AND quantity_in_stick > 0 
AND product_name like %?% 
OR ndc_number like %?%

我认为你想要实现的是最后两个条件是在一起的,就像现在一样,只要包含 OR 语句,它们就会影响整个结果集。你要(product_name like %?% or ndc_number like %?%)

$product = Product::where('user_role_id', '=', 3)
                  ->where('user_id', '!=', $user_id)
                   ->where('quantity_in_stock', '>', 0);
if (!empty($suggestion)) {
    //You can re-assign the variable but I can't remember if you really need it or not, try it out 
    $product = $product->where(function($advancedWhere) use($suggestion) { 
        $advancedWhere->where('product_name', 'like', '%' . $suggestion . '%')
                      ->orWhere('ndc_number', 'like', '%' . $suggestion . '%');
    });
}
$search = $product->orderby('id', 'desc')->get();
$products = $search->toArray();

推荐阅读