代码之家  ›  专栏  ›  技术社区  ›  Crazy Coders

Laravel-如何替换数据库中的字符串

  •  1
  • Crazy Coders  · 技术社区  · 8 年前

    我有一个博客网站。我改名了。所以我需要更改所有包含我品牌的博客帖子。

    我可以发现它们像:

    $search = 'old-brand-name';
    $posts = \App\Models\BlogPost::where('description', 'LIKE', '%'.$search.'%')->get();
    

    但我必须用我的新品牌名称替换数据库级别的这些字符串。我该怎么做?

    3 回复  |  直到 8 年前
        1
  •  2
  •   Duy Huynh    8 年前

    你应该重复每一篇文章,然后通过用新的品牌名称替换旧的品牌名称来更改描述,并更新这篇文章。

    foreach($posts as $post){
        $old_des = $post->description;
        $post->description = str_replace($search,'new-brand-name', $post->description);
        $post->save();
    }
    

    希望对你有帮助

        2
  •  0
  •   Insax    8 年前
    $search = 'old-brand-name';
    $posts = \App\Models\BlogPost::where('description', $search)->update('description', $newName);
    

    只有当“描述”列的内容正好是您的品牌名称时,此操作才有效,否则您必须在“描述”列中提供有关内容的更具体信息。

        3
  •  0
  •   W Kristianto    8 年前

    如果需要更新所有帖子并获取所有结果:

    $old   = 'old-brand-name';
    $new   = 'new-brand-name';
    $posts = \App\Models\BlogPost::where('description', 'LIKE', '%' . $search . '%')
        ->get()
        ->map(function ($item) use ($old, $new) {
            $item->description = str_replace($old, $new, $item->description);
            $item->save();
    
            return $item;
        });
    
    // Print all
    dd($posts->toArray());
    
        4
  •  0
  •   Daedelus    6 年前

    update posts set description = REPLACE(description,'old','new');

    Segundo,使用集合回调而不是foreach,它更具可读性和性能友好。(如map、reduce等)