我正在尝试检查生成的字符串是否在我的数据库表中。
如果没有重复,我想返回并保存。
如果有重复,我想生成一个新字符串并保存 目前此函数不会返回生成的令牌:
public function checkForHashDuplicate($string)
{
$newToken = '';
$inquiries = DB::table('inquiries')->get();
foreach($inquiries as $inquiryKey => $inquiryValue)
{
while($inquiryValue->android_device_token == $string)
{
$newToken = generateAlphanumericString();
if($newToken != $inquiryValue->android_device_token)
{
return $newToken;
}
}
}
}
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
答案 0 :(得分:2)
您的代码的简化版本是:
public function checkForHashDuplicate($string)
{
do {
// generate token
$newToken = generateAlphanumericString();
// find token in a DB
$duplicate = DB::table('inquiries')
->where('android_device_token', '=', $newToken)->first();
// if token is FOUND `$duplicate` has truthy value
// and `do-while` keeps running
// else `$duplicate` is falsy and `do-while` breaks
} while ($duplicate);
return $newToken;
}
答案 1 :(得分:0)
而不是使用:
$inquiries = DB::table('inquiries')->get();
并循环使用where
,如:
$inquiries = DB::table('inquiries')->where('android_device_token', '=', $string)->get();
if( count($inquiries ) == 1 )
{
// found
}
else
{
// Not found, generate new one
}
答案 2 :(得分:0)
您可以这样检查:
public function checkDuplicate($string){
$count = DB::table('inquiries')->where('android_device_token',$string)->count();
if($count==0){
// $string exists
return generateAlphanumericString();
}else{
// $string doesn't exists
return $string;
}
}
现在,使用此功能将$string
或新标记的值指定为
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
希望你明白。