将 json 集合 id 与模型中的数组匹配并添加相应的标签

问题描述

我将情绪数据作为 json 存储在我的记录模型中(我正在加密记录表,不希望通过关系公开数据。):

记录迁移

Schema::create('records',function (Blueprint $table) {
    $table->id();
    $table->text('title')->nullable();
    $table->json('emotions')->nullable();
    $table->timestamps();
});

这是我通过我的记录资源获得的输出:

记录资源

class RecordResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,'title' => $this->title,'emotions' => $this->emotions
        ];
    }
}

输出

"data":[
   {
      "id":91,"title":"Temporibus sed ut voluptas nesciunt.","emotions":[
         {
            "intensity":10,"emotion_id":1,"newIntensity":3
         },{
            "intensity":10,"emotion_id":2,"newIntensity":3
         }
      ]
   },{
      "id":92,"title":"Facilis provident qui tempore sit illum fuga incidunt odio.","newIntensity":3
         }
      ]
   }
]

我想要做的是将情绪标签存储在数据库中或现在仅存储在记录对象的数组中:

class Record extends Model
{
    use HasFactory;

    protected $casts = [
        'emotions' => 'json',];

    public $emtionsLabels = ['Happy','Sad'];
}

然后我想将标签与情绪集合相匹配并添加一个 is_picked 属性,以便输出如下所示:

新输出

"data":[
   {
      "id":91,"newIntensity":3
            "label": "Happy","is_picked": false
         },"newIntensity":3
            "label": "Sad","is_picked": false
         }
      ]
   },"is_picked": false
         }
      ]
   }
]

我打算尝试将情绪赋予它自己的资源 'emotions' => EmotionResource::collection(json_decode($this->emotions,true)) 以便我可以在那里构建 json 输出,但是我遇到了很多问题:

试图获取非对象的属性“强度”

class EmotionResource extends JsonResource
{
    public function toArray($request)
    {
        return ['intensity' => $this->intensity];
    }
}

更新 1

在我的 RecordController 中,我设法获得了我想要的情绪输出:

class RecordController extends Controller
{
    public function index()
    {

        $emotions = Record::first()->emotions;

        $phpRecords = json_decode($emotions,true);

        $newEmotions;
        $record = new Record();
        $labels = $record->emtionsLabels;
        foreach($phpRecords as $emotion){
            $newEmotions[] = 
                [
                    'intensity' => $emotion['intensity'],'new_intensity' => $emotion['newIntensity'],'emotion_id'=> $emotion['emotion_id'],'label' => $labels[$emotion['emotion_id'] - 1]
                ];
        }

        return collect($newEmotions);

    }
}

我只需要弄清楚如何在 EmotionResource 或 RecordResource 中执行此操作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)