php - Laravel中的数字范围交集搜索
问题描述
我有 2 列from和to的记录 用户可以通过从ant选择 或输入值来过滤结果如何使用 Laravel 正确实现这个东西 我现在拥有的很简单
$query->where("field_to", '<=', $field_to);
$query->where("field_from", '>=', $field_from);
但这将不起作用,例如,如果数据库中的值为 10 和 100,但用户输入 50 和 200。我需要某种交集检查。还是我过度设计了一些东西?
解决方案
你必须使用这样的东西:
$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:赶上
推荐阅读
- typescript - 提供 const 变量接口时出现打字稿错误
- python - AttributeError:比较数据时,“NoneType”对象没有属性“数据”
- javascript - 未捕获的类型错误:无法读取未定义的属性“选择”
- java - 在这种情况下如何将数据从 JFrame 传输到另一个 JFrame?
- eclipse - 支持哪些 MagicDraw eclipse 插件符号?
- kubernetes - 如何分发 Kubernetes 配置
- java - Android:对于某些应用程序,UsageStats 在 getTotalTimeInForeground() 上返回 0
- ansible - 根据服务器类型选择正确的文件
- android - 在android中实现hilt库时gradle出错
- python - Python .NET 中的 VB.NET ReDim 数组