问题描述
我将情绪数据作为 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 中执行此操作。
解决方法
我用上面更新的代码创建了一个访问器:
class Record extends Model
{
use HasFactory;
/*protected $casts = [
'emotions' => 'json',];*/
public $emtionsLabels = ['Happy','Sad'];
public function getEmotionsAttribute($value)
{
$emotions = json_decode($value,true);
foreach($emotions as $emotion){
$newEmotions[] =
[
'intensity' => $emotion['intensity'],'new_intensity' => $emotion['newIntensity'],'emotion_id'=> $emotion['emotion_id'],'label' => $this->emtionsLabels[$emotion['emotion_id'] - 1]
];
}
return collect($newEmotions);
}
}