如何编写Laravel迁移将项目表分类字段转为多对多关联结构
迁移实现代码修正
你现有代码存在两个核心问题:
- 分类插入的
insert方法参数格式错误,需要传入二维数组而非多个独立一维数组 - 直接用
like匹配分类名称会出现误判(比如category_1会匹配到包含category_11的记录),需要先把存储的PHP数组字符串反序列化为实际数组再做匹配
完整可运行的迁移代码如下:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\DB; class CreateCategoriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // 创建分类表 Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('parent_id')->nullable(); $table->string('title'); $table->timestamps(); $table->softDeletes(); }); // 批量插入分类,注意insert方法接收二维数组 DB::table('categories')->insert([ ['title' => 'category_1'], ['title' => 'category_2'], ['title' => 'category_3'], ['title' => 'category_4'], ['title' => 'category_5'] ]); // 创建项目和分类的关联表 Schema::create('categories_projects', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('project_id'); $table->unsignedInteger('category_id'); // 新增联合唯一索引,避免重复关联生成脏数据 $table->unique(['project_id', 'category_id']); $table->timestamps(); $table->softDeletes(); }); // 处理已有项目的分类关联 $allCategories = DB::table('categories')->pluck('id', 'title')->toArray(); // 用chunk分批读取项目数据,避免数据量过大时内存溢出 DB::table('projects')->orderBy('id')->chunk(100, function ($projects) use ($allCategories) { foreach ($projects as $project) { // 正则提取分类名称,替代eval避免安全风险 preg_match_all("/'([^']+)'/", $project->categories, $matches); $projectCategories = $matches[1] ?? []; // 组装关联数据批量插入 $insertData = []; foreach ($projectCategories as $catTitle) { if (isset($allCategories[$catTitle])) { $insertData[] = [ 'project_id' => $project->id, 'category_id' => $allCategories[$catTitle] ]; } } if (!empty($insertData)) { DB::table('categories_projects')->insert($insertData); } } }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('categories_projects'); Schema::dropIfExists('categories'); } }
注意事项
- 迁移执行前建议先备份
projects表数据,避免数据异常 - 如果你的存储格式里用的是双引号包裹分类名,调整正则匹配规则即可
- 完成迁移验证数据无误后,可再写一个迁移删除
projects表废弃的categories字段
内容的提问来源于stack exchange,提问作者dan178
相关产品推荐
相关产品推荐

