Laravel Eloquent的orWhere未按预期工作。

huangapple go评论67阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2020年1月4日 12:22:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59587858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定