首页 > 解决方案 > Laravel中的数字范围交集搜索

问题描述

我有 2 列fromto的记录 用户可以通过ant选择 或输入值来过滤结果如何使用 Laravel 正确实现这个东西 我现在拥有的很简单

$query->where("field_to", '<=', $field_to);
$query->where("field_from", '>=', $field_from);

但这将不起作用,例如,如果数据库中的值为 10 和 100,但用户输入 50 和 200。我需要某种交集检查。还是我过度设计了一些东西?

标签: phplaravel

解决方案


你必须使用这样的东西:

$field_to = 50;
$field_from = 200;

$query->where(function ($query) use ($field_from) {
    $query->where('field_from', '<=', $field_from)
        ->where('field_to', '>=', $field_from);
})
->orWhere(function ($query) use ($field_to) {
    $query->where('field_from', '<=', $field_to)
        ->where('field_to', '>=', $field_to);
});

这将抓住你的情况。例如,如果数据库中的记录是 50 和 100,并且用户输入这些值:

  • 55 和 70:赶上
  • 70 和 150:赶上
  • 150 和 200:未捕获
  • 20 和 30:没有抓住
  • 20 和 75:赶上

推荐阅读