php - Laravel 在 MySQL 中的 JSON 字段的帮助下创建 API 返回

标签 php mysql json laravel eloquent

我有一个要求,其中我将创建一个 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/

相关文章:

PHP 数据库中的错误字符集

php - 如何在 PHP 中创建一个预定义大小的空数组?

java - 存储上次登录时间戳

python - 检查字典键名称,它是类的实例

json - 无法将字符串映射转换为 json

php - 为什么html页面读不到php页面

php - 错误 310 (net::ERR_TOO_MANY_REDIRECTS):重定向过多。为 Facebook 使用 PHP SDK

PHP和Ajax上传

java - JPA(ebean)部分mysql日期

python - 将 Python 字典中的 JSON 值累积为数组