我需要复制数据库中的记录,如果存在则在名称旁边添加一个数字,例如:
MyRecord
MyRecord Duplicate 1
如果我再次复制
我的记录重复2,依此类推......
我试过了
foreach($records as $record) {
$nombre = $record->name;
$newName= $record->name." - DUPLICATED 1";
//If exists
if ($nombre = $newName) {
$valor = substr($nombre, -1); //Get last value of string, it will be the number, its always at the end.
$num = $valor;
$int = (int)$num;
$float = (float)$num;
$float++;
$newName= $record->name." - DUPLICATED ".$float;
//Second try
if ($nombre = $newName) {
$valor = substr($nombre, -1);
$num = $valor;
$int = (int)$num;
$float = (float)$num;
$float++;
$today = Carbon::now();
DB::table('table')->insert( ...
问题是,当foreach再次出现时,它试图在名称上插入一个重复的值,所以我现在有
名称重复1
名称重复2
名称复制2 - >而不是3
答案 0 :(得分:0)
好的,我以这种方式得到它
do {
//do while name exists
$clone++;
$newName = $record->name." - CLONED - ".$clone;
$nameExists= DB::table('record')
->where('name', '=', $newName)
->first();
} while ($nameExists);