【问题标题】:laravel, query builder, (or)where query not working as expectedlaravel,查询生成器,(或)查询未按预期工作
【发布时间】:2018-08-08 06:22:50
【问题描述】:

这是我的 laravel 查询

$Product = Product::select('id','ProductWorkpiece','ProductCategory','ProductName','ProductImage','ProductSubCategory')
        ->where('ProductCategory',$category)
        ->where(function ($query) use ($ProductWorkpiece,$ProductMaterial,$ProductSubCategory,$ProductBrand) {

     foreach($ProductBrand as $key => $ProductBrandd) {
                if (!empty($ProductBrandd) && empty($subcategory)) {
                $query->orWhere('ProductBrand', '=', $ProductBrandd);
                    }
                 foreach($ProductSubCategory as $key => $subcategory) {
                if (!empty($ProductBrandd) && !empty($subcategory)) { 
                  $query->where('ProductSubCategory', '=', $subcategory);
                        }
                    }
                }
    })->where('Status','=','1')->get();

实际上有效,但有一个奇怪的,当我点击 1 复选框有效,但当我点击 2 为什么无效 举例 我有一个名为 sisma 的品牌,并且有 2 个名为激光打标机品牌 sisma 的产品子类别 当我检查品牌 sisma 时,出了 2 个产品 当我检查子类别点标记机时,两个项目都丢失了。没错 当我检查子类别激光打标机和 2 时,产品没有出来,当我取消选中点打标机时,东西出来了 我觉得奇怪的是它应该没有未经检查的可以看到 2 产品

如果你还是不明白,看这个视频只有 12 秒 https://youtu.be/fY417NsZmHI

这是我的手动sql,效果很好

SELECT * FROM Product WHERE ProductCategory = 'Marking' AND ProductBrand = 'Sisma' and ProductSubCategory = 'Dot Marking Machine' 
or ProductSubCategory = 'Laser Marking Machine' 

$ProductSubCategory 的内容和类型

Array
(
    [0] => Dot Marking Machine
    [1] => Laser Marking Machine
)

$ProductBrand 的内容和类型

Array
(
    [0] => Sisma
)

【问题讨论】:

    标签: php mysql sql laravel laravel-5


    【解决方案1】:

    像这样重写查询有助于获得所需的结果组合

    $Product = Product::select('id','ProductWorkpiece','ProductCategory','ProductName','ProductImage','ProductSubCategory')
              ->where('ProductCategory',$category)
              ->where('Status', '1')
              ->whereIn('ProductBrand', $ProductBrand)
              ->where(function ($query) use ($ProductWorkpiece,$ProductMaterial,$ProductSubCategory,$ProductBrand) {
                  foreach($ProductSubCategory as $key => $subcategory) {
                    if (!empty($subcategory)) { 
                      $query->orwhere('ProductSubCategory', '=', $subcategory);
                    }
                  } })->get(); 
    

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 1970-01-01
      • 2012-11-13
      • 2019-04-12
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多