首页 > 解决方案 > 在 Laravel 中使用数组过滤产品

问题描述

我正在尝试使用主题过滤应用程序产品,我使用 ajax 将主题数组发送到控制器,并在控制器中尝试使用以下代码获取产品:

for($j=1;$j <=sizeof($request->subjects);$j++) 
{
 $product_id= Productsubject::where('subject', $request->subjects[$j - 1])- 
 >pluck('product_id');
 $products = Product::whereIn('id',$product_id)->get();
}
echo $products;

当我运行时,我只给出主题数组的最新对象的产品,例如我的主题是[art,math]我只给出带有数学主题的产品,我怎样才能给所有带有艺术和数学主题的产品?

标签: laravelfilter

解决方案


您正在运行一个新查询并在循环的每次迭代中覆盖产品。

您正在使用 whereIn 进行第二个查询。为什么不同时使用它并放弃循环?

$productIds = Productsubject::whereIn('subject', $request->subjects)->pluck('product_id');
$products = Product::whereIn('id', $productIds)->get();

推荐阅读