组合在哪里和哪里不起作用

时间:2020-10-21 13:07:19

标签: php laravel

我在此行下有问题代码不起作用!我该如何工作? ... ... orWhere orWhere会进行过滤,但会累积查询。哪里……没有提供任何结果。有人可以帮我吗?

$artworks = Artwork::where('category_id', $category)
    ->where('style_id', $style)
    ->where('technic_id', $technic)
    ->where('orientation', $orientation)
    ->get();

这是完整的代码:

if (request()->category_id) {
                $category = request()->category_id;
            } else {
                $category = 0;
            }

            if (request()->style_id) {
                $style = request()->style_id;
            } else {
                $style = 0;
            }

            if (request()->technic_id) {
                $technic = request()->technic_id;
            } else {
                $technic = 0;
            }

            if (request()->orientation_id == 'vertical') {
                $orientation = 'vertical';
            } else if (request()->orientation_id == 'horizontal') {
                $orientation = 'horizontal';
            } else {
                $orientation = 0;
            }


            $artists = Artist::get();
            $artworks = Artwork::where('category_id', $category)
                ->where('style_id', $style)
                ->where('technic_id', $technic)
                ->where('orientation', $orientation)
                ->get();
            
            return view('frontend.index', compact('artworks', 'artists'));

2 个答案:

答案 0 :(得分:0)

我认为您想使用OR条件,并且误以为double where。请看下面以正确理解

如果您要在查询中使用AND条件,则使用double在哪里,但是如果您想要OR条件,则必须使用orWhere

示例:

AND条件

Query::where(condition)->where(condition)->get();

OR条件

Query::where(condition)->orWhere(condition)->get();

答案 1 :(得分:0)

如果您希望设置所有变量

如果查询变量category_idstyle_idorientation_idtechnic_id不正确,则默认为0。

您的查询很好,但是您可能没有想要的数据。

在此功能的顶部运行以下命令:

print_r($request->all());
exit;

如果所有变量都是可选的

实现此目标的非常程序化的基本方法:

            $artists = Artist::get();
            $artworks = Artwork::where('id', '>', 0);

            $category_id = request()->input('category_id');
            if ($category_id != '') {
                $artworks->where('category_id', request()->category_id);
            }

            $style_id = request()->input('style_id');
            if ($style_id != '') {
                $artworks->where('style_id', request()->style_id);
            }

            $technic_id = request()->input('technic_id');
            if ($technic_id != '') {
                $artworks->where('technic_id', request()->technic_id);
            }

            $orientation_id = request()->input('orientation_id');
            if ($orientation_id != '') {
                $artworks->where('orientation_id', request()->orientation_id);
            }

            $artworks->get();
            
            return view('frontend.index', compact('artworks', 'artists'));
相关问题