2017-05-09 61 views
1

我需要复制的数据库中的记录,并且如果存在的话旁边加上一个数字来命名,例如:重复记录添加一个号码,如果存在

MyRecord

MyRecord重复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谈到它再次trieds插入值作出名字重复,所以我现在有

名称重复1

名称重复2

名称重复2 - 的>,而不是3

+0

'if($ nombre = $ newName)'我相信你在这里分配,而不是比较'if($ nombre == $ newName)' –

+0

问题是,它似乎没有找到最新的记录名字......我认为这个问题,所以如果有一个相同的名字只是做了float ++,它会有一个新的名字......那是我的逻辑......也许我错了。 – lucasvm1980

回答

0

好吧,我得到它以这种方式

do { 
       //do while name exists 
       $clone++; 
       $newName = $record->name." - CLONED - ".$clone; 
       $nameExists= DB::table('record') 
            ->where('name', '=', $newName) 
            ->first(); 

      } while ($nameExists); 
相关问题