英文:
Laravel Eloquent orWhere not working as expected
问题
这个Eloquent查询似乎不按预期工作。
如果我先传入一个术语(term),然后是类别(category),再然后是制造商(manufacturer),它就按预期工作,但只输入制造商会得到零结果,类似地,输入类别也是如此。
以下是我的URL...
/products?term=12&category=2&manufacturer=3
这是toSql()的输出:
"select * from products
where id
= ? or model
like ? or category_id
= ? or manufacturer_id
= ?"
$term = $request->input('term');
$category = $request->input('category');
$manufacturer = $request->input('manufacturer');
$products = Product::orWhere('id', $term)
->orWhere('model', 'like', "%{$term}%")
->orWhere('category_id', $category)
->orWhere('manufacturer_id', $manufacturer)
->get();
陷入困境,非常感谢任何帮助。
英文:
This Eloquent query does not seem to be working as expected.
If I pass in a term then category then manufacturer it works as expected, but only entering a manufacturer yields zero results and likewise with manufacturer.
Here is my url...
/products?term=12&category=2&manufacturer=3
Here is the dump of toSql()
"select * from products
where id
= ? or model
like ? or category_id
= ? or manufacturer_id
= ?"
$term = $request->input('term');
$category = $request->input('category');
$manufacturer = $request->input('manufacturer');
$products = Product::orWhere('id', $term)
->orWhere('model', 'like', "%{$term}%")
->orWhere('category_id', $category)
->orWhere('manufacturer_id', $manufacturer)
->get();
Stumped, any help would be greatly appreciated.
答案1
得分: 1
$term = $request->input('term');
$category = $request->input('category');
$manufacturer = $request->input('manufacturer');
$products = Product::where(function ($query) use ($request, $term, $category, $manufacturer) {
if ($request->filled('term'))
$query->orWhere('model', 'like', "%{$term}%")->orWhere('id', $term);
if ($request->filled('category'))
$query->orWhere('category_id', $category);
if ($request->filled('manufacturer'))
$query->orWhere('manufacturer_id', $manufacturer);
})->latest()
->paginate(5);
英文:
$term = $request->input('term');
$category = $request->input('category');
$manufacturer = $request->input('manufacturer');
$products = Product::where(function ($query) use ($request,$term,$category,$manufacturer) {
if($request->filled('term'))
$query->orWhere('model', 'like', "%{$term}%")->orWhere('id', $term);
if($request->filled('category'))
$query->orWhere('category_id', $category);
if($request->filled('manufacturer'))
$query->orWhere('manufacturer_id', $manufacturer);
})->latest()
->paginate(5);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论