/**
* 递归获取产品编号(支持新增和更新场景)
* @param string $product_no 基础产品编号(如BYDTL20S1PB45-2003)
* @param int $excludeId 排除的ID(更新时传入当前记录ID,避免自身干扰)
* @return string 生成的完整编号
*/
public static function getProductNo($product_no = '', $excludeId = 0)
{
$product_no_main = explode('.', $product_no)[0]; // 提取主编号
// 查询条件:匹配主编号或主编号.xx格式
$query = self::where(function ($query) use ($product_no_main) {
$query->where('product_no', '=', $product_no_main)
->whereOr('product_no', 'like', $product_no_main . '.%');
});
// 若为更新场景,排除当前记录ID
if ($excludeId > 0) {
$query->where('id', '<>', $excludeId);
}
// 获取所有匹配的编号
$list = $query->column('product_no');
if (empty($list)) {
return $product_no_main; // 无记录时直接返回主编号
}
$maxSuffix = 0;
foreach ($list as $no) {
$parts = explode('.', $no);
$suffix = isset($parts[1]) && is_numeric($parts[1]) ? intval($parts[1]) : 0;
if ($suffix > $maxSuffix) {
$maxSuffix = $suffix;
}
}
// 生成新编号(最大后缀+1)
return $maxSuffix > 0
? $product_no_main . '.' . ($maxSuffix + 1)
: $product_no_main . '.1';
}