在 Laravel 9 中使用 where 条件进行 id 循环

id looping with where condition in Laravel 9

提问人:Ye Kyaw 提问时间:9/22/2023 最后编辑:Ye Kyaw 更新时间:9/22/2023 访问量:43

问:

enter image description here我发送了一个包含ajax的数组category_id如图所示。并在控制器中捕获这些类别,以执行与产品表中category_id字段相等的产品行。在这种情况下,我无法将数组循环为从 ajax 发送的数组category_id用于控制器中的 where 条件。请指导我.......

public function productCategoryList(Request $request)
{
    logger($request->status);
    $data = Products::where('category_id', $request->status)->get();
    return $data;
}
PHP jQuery Ajax Laravel Web 应用程序

评论


答:

2赞 Repox 9/22/2023 #1

您可以在查询生成器上使用:whereIn()

public function productCategoryList(Request $request)
{
    logger($request->status);
    $data = Products::whereIn('category_id', $request->status)->get();
    return $data;
}

这将允许您查询元素列表,而不是单个元素。

有关如何使用方法的文档,请访问 https://laravel.com/docs/10.x/queries#additional-where-clauseswhereIn()

评论

0赞 Ye Kyaw 9/25/2023
谢谢Repox..它对我来说工作正常。
0赞 Repox 9/25/2023
@YeKyaw如果我的回答帮助您解决了问题,请考虑接受我的回答。
1赞 darshita_baldha 9/22/2023 #2

您可以使用它允许您根据给定的值数组筛选查询结果。whereIn()

$data = Products::whereIn('category_id', $request->status)->get();

评论

0赞 Ye Kyaw 9/25/2023
非常有用的提示,非常感谢。