Laravel搜索;通过外部表过滤,然后再次使用本地表过滤结果

时间:2018-10-29 10:23:45

标签: php mysql laravel

我有两个表“ stocks”和“ products”。他们有一对多的关系。

型号- Product.php

public function stocks(){
    return $this->hasMany('Modules\Stock\Entities\Stock');
}

模型-Stock.php

public function product(){
    return $this->belongsTo('Modules\Product\Entities\Product')->withTrashed();
}

在搜索股票时,我也要按产品名称搜索。我创建了一个用于搜索关键字的搜索,并为低库存创建了一个可选复选框。因此,如果我要搜索库存不足的产品(例如“鞋子”),则应该向我显示数量少的鞋子。

只要搜索类型在stock表的列中,此方法就可以完美地工作。但是当我想根据产品名称(在产品表中)搜索记录时,然后根据低库存(在产品表中)过滤这些结果记录。没有显示结果。

class ProductName implements Filter
{
   public static function apply(Builder $builder, $value, $checkbox)
   {
      if($checkbox == null) {
         $a = $builder->whereHas ('product', function ($query) use ($value) 
         {
            $query->where('name', 'LIKE', '%' . $value . '%'); //this works fine.
         });
      } else {
        $a = $builder->whereHas ('product', function ($query) use ($value) {
            $query->where('name', 'LIKE', '%' . $value . '%');
        })->whereRaw('quantity < low_stock_threshold'); //This is meant for two search filters;one for searching in product table then filtering the results againtst stock table according to low quantity.
      }
      return $a;
   }
}

注释行不起作用。如果有人可以解决此问题,请提供帮助。

1 个答案:

答案 0 :(得分:2)

我看到了我的sql查询,并根据需要进行了编辑,并且可以正常工作。感谢@Egretos的建议。

class ProductName implements Filter
{
   public static function apply(Builder $builder, $value, $checkbox)
   {
       if($checkbox == null) {
           $a = $builder->whereHas ('product', function ($query) use ($value) {
               $query->where('name', 'LIKE', '%' . $value . '%');
           });
       } else {
           $a = $builder->whereHas ('product', function ($query) use ($value) {
               $query->where('name', 'LIKE', '%' . $value . '%');
           })->whereRaw('`stocks`.`quantity` < `stocks`.`low_stock_threshold`'); //edited this line and it worked.

       }
       return $a;
   }

}
相关问题