blasttech/laravel-where-plus

Laravel Eloquent 的额外 where 范围

2.0.3 2021-07-22 22:47 UTC

README

Laravel 模型的额外 where 范围

函数

  • whereOrEmptyOrNull($column, $value, $ignore)
  • whereInColumn($column, $value)
  • whereNotInColumn($column, $value)
  • whereIfNull($column, $ifNull, $operator = null, $value = null, $boolean = 'and')

whereOrEmptyOrNull

当 $column 应该等于 $value 但不等于 $ignore 时,此操作添加 where 条件

  $query->whereOrEmptyOrNull('Country', $input['country'], '');

如果 $input['country'] 不等于 '',则这相当于

  $query->where('Country', $input['country']);

否则,如果 $input['country'] === '',则不会添加 where 语句。

同样,可以添加一个默认值,例如。

$query->whereOrEmptyOrNull('Country', $input['country'], 'Australia');

如果您只想在 $input['country'] 不为 'Australia' 时添加 where 语句。

这也可以用列的数组运行,例如。

  $query->whereOrEmptyOrNull([
          'Country' => $input['country'],
          'State' => $input['state'],
          'Locality' => $input['locality']
      ], '', '');

这将添加 Country、State 和 Locality 的 where 语句,如果输入字段不为空。

whereInColumn

这仅添加 $value 在 $column 中的 where 条件。$column 的值应该是以逗号分隔的列表。

例如

  $query->whereInColumn('Country', 'Australia');

在 SQL 中,这相当于

  WHERE CONCAT(',', `Country`, ',') LIKE '%,Australia,%'

whereNotInColumn

这仅添加 $value 不在 $column 中的 where 条件。$column 的值应该是以逗号分隔的列表。

例如

  $query->whereNotInColumn('Country', 'Australia');

在 SQL 中,这相当于

  WHERE CONCAT(',', `Country`, ',') NOT LIKE '%,Australia,%'

whereIfNull($column, $ifNull, $operator = null, $value = null, $boolean = 'and')

这添加了一个带有 SQL 'IFNULL' 包裹的列的 where 条件,列作为第一个参数,$ifNull 作为第二个参数。

例如

  $query->whereIfNull('Country', 'Australia', '=', 'New Zealand');

在 SQL 中,这相当于

  WHERE IFNULL(`Country`, 'Australia') = 'New Zealand'

聚合

可用范围

  • addCount
  • addSum
  • addAvg
  • addMin
  • addMax

示例

Calls::make()
  ->select(['calltype'])
  ->addCount('id')
  ->addSum('seconds')
  ->addSum('seconds', 'seconds2')
  ->groupBy('calltype');

在 SQL 中,这相当于

  select calltype, count(id), sum(seconds), sum(charge) 
    from calls 
   group by calltype

分组和排序

可用范围

  • groupByIndex
  • orderByIndex

示例

Calls::make()
  ->select(['calltype', 'description'])
  ->addSum('charge')
  ->groupByIndex(1, 2);
  ->orderByIndex(1);
  select calltype, description, sum(charge) 
    from calls 
   group by 1, 2
   order by 1