【问题标题】:Laravel search; filter by a foreign table then again filter results with the local tableLaravel 搜索;按外部表过滤,然后再次使用本地表过滤结果
【发布时间】:2018-10-29 10:23:45
【问题描述】:

我有两个表“股票”和“产品”。他们有一对多的关系。

型号 - 产品.php

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

模型 - Stock.php

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

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

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

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;
   }
}

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

【问题讨论】:

  • 你能显示 SQL 查询吗? echo $a-&gt;toSql(); die;
  • select * from stocks where exists (select * from products where stocks.product_id = products.id and name LIKE ?) 和数量 stocks.deleted_at 为空

标签: php mysql laravel


【解决方案1】:

我看到了我的 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;
   }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多