【问题标题】:Laravel store JSON data API to databaseLaravel 将 JSON 数据 API 存储到数据库
【发布时间】:2021-06-10 16:14:16
【问题描述】:

我从 API 获得数据 json,我想将它们存储到我的数据库中。

数据 json 样本:

{
    "success": true,
    "data": [
        {
            "status_employee_id": "1",
            "name": "Manager"
        },
        {
            "status_employee_id": "2",
            "name": "Staff"
        },
        {
            "status_employee_id": "3",
            "name": "OB"
        },
        {
            "status_employee_id": "4",
            "name": "Fired"
        },
        {
            "status_employee_id": "5",
            "name": "Retired"
        }
    ]
}

我的模型

class StatusEmployee extends Model
{
    use HasFactory;
    protected $table = 'status_employee';
    protected $fillable = [
       'status_employee_id','name'
    ];
    public $timestamps = false;

}

我已经尝试在我的控制器中使用它

public function store()
    {
        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', 'http://xx.xx.xx.xx/tools/public/get_status_employee');
        $datas = json_decode($res->getBody(), true);
        foreach($datas as $data){
            StatusEmployee::create([
                'status_employee_id' => $data->status_employee_id,
                'name' => $data->name,
            ]);
        }


    }

我想将数据 json 样本存储到我的表 status_employee。如何制作?

【问题讨论】:

  • 到目前为止你尝试过什么?问题是什么?

标签: laravel api rest laravel-8


【解决方案1】:

我假设你使用 Laravel,因为你在标签中提到了 Laravel。

    DB::table('status_employee')->insert(json_decode($res->getBody(),true)['data']);

【讨论】:

  • 我在我的问题中添加了更多细节控制器
【解决方案2】:

很简单,Laravel Eloquent 会为你做一切。

// If json is in string decode first
$data = json_decode($res->getBody(), true); // to array

// Eloquent approach
StatusEmployee::insert(@$data['data']); 

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 2020-01-15
    • 2020-06-09
    • 2023-03-05
    • 2017-08-03
    • 2019-03-23
    • 2021-11-24
    • 2018-03-04
    • 1970-01-01
    相关资源
    最近更新 更多