首页 > 解决方案 > Laravel - 如何替换数据库中的字符串

问题描述

我有一个博客网站。我改变了我的品牌名称。所以我需要更改所有包含我的品牌名称的博客文章。

我可以像这样找到它们:

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

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

标签: phpmysqllaravellaravel-5

解决方案


您应该迭代每个帖子,然后通过将 old_brand_name 替换为 new_brand_name 来更改描述并更新此帖子。

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

希望它可以帮助你


推荐阅读