Php 使用whereHas查询数组

Php 使用whereHas查询数组,php,laravel,eloquent,Php,Laravel,Eloquent,我想按类别筛选产品(多个关系)。基本上,用户可以选择要显示的类别。我要筛选的类别位于$request->keywords中。这就是我所尝试的: $products = Product::all(); foreach($request->keywords as $keyword) { $products = Product::whereHas('categories', function($q) use ($keyword){ $q->where('titl

我想按类别筛选产品(多个关系)。基本上,用户可以选择要显示的类别。我要筛选的类别位于
$request->keywords
中。这就是我所尝试的:

  $products = Product::all();
  foreach($request->keywords as $keyword) {
    $products = Product::whereHas('categories', function($q) use ($keyword){
      $q->where('title', '=', $keyword);
    })->get();
  }

  return response()->json($products);
问题是,这并不能获取所有类别,只能获取阵列中最后一个类别的产品。我猜在这一点上:
$q->where('title','=',$keyword)
$q
不保留最后一次循环迭代的结果,但始终删除最后一次循环结果。 我还用
$q->orWhere('title','=',$keyword)尝试了同样的方法,但这实际上并没有给我任何结果


谢谢你的帮助

您只需在标题字段中输入关键字即可使用
,其中

$products = Product::all();
$titles = [];
foreach($request->keywords as $keyword) {
    $titles[] = $keyword;
}
$products = Product::whereHas('categories', function($q) use ($keyword){
    $q->whereIn('title', $titles);
})->get();

更改了获取数据的方法

$products = Product::all();
if (!empty($request->keywords)) { // if keywords not empty
    $keyword  = $request->keywords;
    $products = Product::whereHas('categories', function ($q) use ($keyword) {
        $q->whereIn('title', $keyword); // where in for array
    })->get(); // it won't override old data as there is no loop
}

return response()->json($products);

我正在改进其他人的回答。下面是这里的过滤代码

$builder = new Product;

if($request->filled('keywords')) {  // if keywords key has any value then query will execute.

    $builder = $builder->whereHas('categories', function($q) use ($request){
                        $q->whereIn('title', array_values($request->keywords));
                    });
}

$items = $builder->get();
dd($items);

您可以试试这个。

太好了,非常感谢!所以我想问题是我没有使用
,其中
?如果您将我的代码片段与您的代码片段进行比较,您部分是对的