我在Laravel 5应用程序中为每个客户生成订单后的客户id。下面是为客户生成ID的代码,该ID由客户的姓和名的一部分组成,如果生成了重复的ID,则会添加一个随机字符串。
$ID = strtolower(substr($itemsP['firstName'],0,2) . $itemsP['lastName']);
function checkforduplicateID($iD,$firstName,$lastName)
{
$f = $firstName;
$l = $lastName;
$orders = Order::where('customerID',$iD)->get()->count();
if($orders>0)
{
$ID = strtolower(substr($firstName,0,2) . $lastName . substr(md5(rand()),0,2));
checkforduplicatecode($ID,$f,$l);
}
else
{
return $iD;
}
}
$sessionOrder->customerID = checkforduplicateID($ID,$itemsP['firstName'],$itemsP['lastName']);
$sessionOrder->save();
在第一次循环时(没有重复),这工作得很好。但是,只要我有两个具有相同姓和名的客户,该函数就会返回一个null
,而不是带有附加(随机)字符串的相同ID。
因此,我在倒数第二行上得到了完整性冲突,因为我将null
插入到数据库中。
我的checkforduplicateID
功能明显有问题,但我不知道是什么。
请协助。
我相信这里
if($orders>0) {
$ID = strtolower(substr($firstName,0,2) . $lastName . substr(md5(rand()),0,2));
checkforduplicatecode($ID,$f,$l);
} else {
你需要像这样返回新的ID:
if($orders>0) {
$ID = strtolower(substr($firstName,0,2) . $lastName . substr(md5(rand()),0,2));
return checkforduplicateID($ID,$f,$l);
} else {