Browse Source

fix:数据

super-yimizi 3 weeks ago
parent
commit
80616d75db
1 changed files with 20 additions and 1 deletions
  1. 20 1
      application/common/model/BodyTypeSelection.php

+ 20 - 1
application/common/model/BodyTypeSelection.php

@@ -40,13 +40,32 @@ class BodyTypeSelection extends Model
      */
      */
     public static function saveUserSelections($profileId, $selections)
     public static function saveUserSelections($profileId, $selections)
     {
     {
-        if (empty($selections) || !is_array($selections)) {
+        if (!is_array($selections)) {
             return false;
             return false;
         }
         }
 
 
         // 开启事务
         // 开启事务
         \think\Db::startTrans();
         \think\Db::startTrans();
         try {
         try {
+            // 1. 获取当前用户已有的所有选择记录
+            $existingSelections = self::where('profile_id', $profileId)->select();
+            $existingCategories = [];
+            foreach ($existingSelections as $existing) {
+                $existingCategories[] = $existing->type_category;
+            }
+
+            // 2. 获取新传入的分类
+            $newCategories = array_keys($selections);
+
+            // 3. 删除那些在数据库中存在但新数据中不存在的记录
+            $categoriesToDelete = array_diff($existingCategories, $newCategories);
+            if (!empty($categoriesToDelete)) {
+                self::where('profile_id', $profileId)
+                    ->where('type_category', 'in', $categoriesToDelete)
+                    ->delete();
+            }
+
+            // 4. 处理新数据:更新或创建
             foreach ($selections as $category => $typeId) {
             foreach ($selections as $category => $typeId) {
                 // 检查是否已存在该分类的选择
                 // 检查是否已存在该分类的选择
                 $existing = self::where([
                 $existing = self::where([