我有一个名为
ClientDiscountRate
的模型,它自然对应着一张桌子。
我正在开发一种方法来允许创建新的
ClientDiscountRate
。但是,我面临一个问题:client_discount_rates
表有from
和to
列,我需要确保新费率不会与任何现有费率重叠。
from
和to
都必须是整数,且from
小于to
。
例如,如果我已经有从 4 到 6 的范围,则没有重叠范围意味着新汇率不能具有 4、5 或 6 的
from
或 to
值。这也意味着新汇率不能包含 4 -6,例如有from: 3, to: 7
。新范围可以位于现有范围之前或之后,但它不能以任何方式包含、被包含或与现有范围相交。
此外,我可以有多个现有范围。因此,如果我有范围 4-6 和 10-20,则重叠检查必须对两个范围应用相同的逻辑 - 新范围不能重叠、包含或被任何现有范围包含。
我编写了以下代码,但我不确定这是否是最有效的方法:
$from = $requestData['from'];
$to = $requestData['to'];
$matching = ClientDiscountRate::where('client_id', $client->id)
->where('from', '<=', $from)
->where('to', '>=', $from)
->first();
if ($matching) return response()->json(['error' => 'this range overlaps an existing one - from'], 400);
$matching = ClientDiscountRate::where('client_id', $client->id)
->where('from', '<=', $to)
->where('to', '>=', $to)
->first();
if ($matching) return response()->json(['error' => 'this range overlaps an existing one - to'], 400);
$matching = ClientDiscountRate::where('client_id', $client->id)
->where('from', '>=', $from)
->where('from', '<=', $to)
->first();
if ($matching) return response()->json(['error' => 'this range contains an existing one'], 400);
$matching = ClientDiscountRate::where('client_id', $client->id)
->where('to', '>=', $from)
->where('to', '<=', $to)
->first();
if ($matching) return response()->json(['error' => 'this range contains an existing one'], 400);
以上是检查
from
和 to
字段中是否存在不需要的重叠的明智方法吗?
要遵守的规则是,对于数据库中所有小于或等于您的
from
的 $to
,您必须找到那些 to
对应的所有 from
必须小于您的 $from
,如果不是这种情况,那么你就有重叠的范围。
$from = $requestData['from'];
$to = $requestData['to'];
$matching = ClientDiscountRate::where('client_id', $client->id)
->where('from', '<=', $to)
->where('to', '>=', $from)
->exists();
if ($matching) return response()->json(['error' => 'this range overlaps an existing one'], 400);