Laravel-如何使用Guzzle将外部api消耗并刷新到db中

问题描述 投票:2回答:2

我在Laravel-5.8项目中拥有此模型:

员工

class Employee extends Model
{
   protected $table = 'employees';

   protected $primaryKey = 'id';

   protected $fillable = [
              'staff_code',
              'first_name',
              'last_name',
              'department_id',
          ];

  public function department()
  {
     return $this->belongsTo('App\Department','department_id');
  }    

}

即,:

App \ Employee

而且我还有一个以JSON get请求形式出现的外部api。

https://api.employees.net/allemployees

我已经与邮递员获取请求一起查看了,我有这样的东西:

 {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DepartmentCode": "dep2",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DepartmentCode": "dep2",
 },

依此类推...继续。

我已经创建了此功能:

 use App\Employee;
 use App\Department;

 public function index() 
 {  
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res, true);

   ...
 }

除了id和staff_code都是唯一的之外,其他任何字段也可以从源中更改。

由于任何字段都可以随时更改。如何刷新整个数据库,保存新数据并更新更改?

谢谢

laravel guzzle
2个回答
0
投票

我可以做这样的事情:

use App\Employee;
use App\Department;

public function index() 
{  
      $client = new GuzzleHttp\Client();
      $res = $client->request('GET','https://api.employees.net/allemployees');
      $clientdatas = json_decode($res->getBody()->getContents(), true);

      foreach($clientdatas as $clientdata)
      {
            $employee = Employee::firstOrNew(['id' => $clientdata['ID']]);
            $employee->staff_code = $clientdata['StaffCode'];
            $employee->first_name = $clientdata['FirstName'];
            $employee->last_name = $clientdata['LastName'];
            $employee->save();
      }
}

每次您都会进行API调用,创建员工模型的实例,或者如果ID存在,则获取关联的模型。然后分配新值并保存模型。这样,您将能够在一个循环中创建或更新模型而没有任何复杂性。


0
投票

不知道它是否行得通,但是您可以保持逻辑。在另一个答案中,他正在一个不好的循环下查询!

希望对您有所帮助

public function index() {  
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res->getBody()->getContents(), true);
    // create a blank array for insert
    $insert_arr = [];
    foreach($clientdatas as $clientdata) {
        $make_array = [
            'id' => $clientdata['ID'],
            'staff_code' => $clientdata['StaffCode'],
            'first_name' => $clientdata['FirstName'],
            .
            .
        ];
        array_push($insert_arr, $make_array);
        // Now the the $insert_arr will ready for insert
    }
    // Here you have to check its duplicate or not  
    $exist_in_db = Employee::all('id')->toArray(); // get the id array from db

    // do the stuff for unset the duplicate 
    $final_id = array_map(function($value) {
        return $value['id'];
    }, $team_id);
    unset($exist_in_db);
    if(count($final_id) > 0){
        foreach ($insert_arr as $key => $value) {
            if (in_array($value['id'], $final_id)) {
                unset($insert_arr[$key]);
            } else {
                array_push($final_id, $value['id']);
            }
        }
    }

    // finally insert it here
    if (count($insert_arr) > 0) {
        Employee::insert($insert_arr);    
    }
}

让我知道它是否有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.