我有一个要求,其中我将创建一个 JSON 响应。该事件仅有效一天。因此,为了避免创建 JSON 响应,我可以将其存储在 MySQL 数据库中。问题是我能够创建 JSON 响应,并将其保存在 MySQL JSON 字段中。但是,我无法直接通过 MySQL 字段返回响应。
//getting the value's from db
$news = DB::table('news')->where('news_item_name', $news_id)->first();
// checking if the news json values are still active(Cron job will delete expired news articles)
if (isset($news->news_expiry)) {
//this part is not working
return response()->json($news->news_content);
}
//if no news exits create new JSON and save it in the database.
$array = [];
$array[0]['title'] = "some news";
$array[0]['link'] = "http://www.example.com/";
$array[0]['source'] = "example.com ";
$array[0]['description'] = "some news description";
$array[0]['thumbnail']="http://www.example.com/images/sample.png";
//insert fresh news json with an expiry time.
DB::table('news')->insert(
['news_item_name' => $news_id, 'news_content' => json_encode($array), 'news_expiry' => some_expiry_time]
);
return response()->json($array);
最佳答案
如果只是这种情况,你可以使用这个:
//insert of news json with an expiry time.
$saved = DB::table('news')->insert([
'news_item_name' => $news_id,
'news_content' => json_encode($array), 'news_expiry' => some_expiry_time
]);
return response()->json($saved->news_content);
但是如果可以更改为 Elequent 并在模型中使用 Laravel getter 和 setter,您可以这样做:
在插入之前设置一个值
public function setNewsContentAttribute($value)
{
$this->attributes['news_content'] = json_encode($value);
}
获取值
public function getNewsContentAttribute()
{
return json_decode($this->news_content);
}
检查 Laravel 文档中的 elequent
关于php - Laravel 在 MySQL 中的 JSON 字段的帮助下创建 API 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53922262/