mysql - 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。
可以帮助解决这个问题。
谢谢
解决方案
那是因为您的查询被翻译为:
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();
推荐阅读
- python - 如何在不迭代的情况下根据特定对从数据框中选择结果?
- python - 如何从多个每日文件中获取运行平均值或移动平均值
- angularjs - 如何使用 mat-slide-toggle 禁用角度输入字段?
- c++ - 如何生成无限随机数的一对骰子直到它们相等?
- javascript - 多次调用多次链接 Promise.all() 的最佳方式
- php - 为什么 count() 会覆盖一个值?
- react-native - React 本机 Firebase 版本使应用程序崩溃
- python - 是否可以使用 batch_create_entities() 上传 KIND_MAP 实体?
- javascript - 在ajax url页面执行Javascript代码并显示结果
- python - 在 Python 中使用基类构造函数声明子类的优点