laravel - 在 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]
我只给出带有数学主题的产品,我怎样才能给所有带有艺术和数学主题的产品?
解决方案
您正在运行一个新查询并在循环的每次迭代中覆盖产品。
您正在使用 whereIn 进行第二个查询。为什么不同时使用它并放弃循环?
$productIds = Productsubject::whereIn('subject', $request->subjects)->pluck('product_id');
$products = Product::whereIn('id', $productIds)->get();
推荐阅读
- mysql - localhost 说请输入有效长度
- angular - 使用异步管道一个接一个地执行 Observable
- angularjs - 如果我打开两个相同的 angularjs 应用程序,rootScope 是否相同?
- javascript - JavaScript HTML 日期选择器
- javascript - 如何只运行一次javascript函数?
- javascript - 使用 removeChild() 删除损坏的图像?
- sql-server - jpa'limit'附近的语法不正确
- javascript - 刷新页面,直到特定字符串出现在页面的某个部分
- angular - 输入占位符中显示的表单验证器
- ios - 使用 Alamofire 解析可编码响应