【问题标题】:Laravel - How to consume and refresh external api into db using GuzzleLaravel - 如何使用 Guzzle 使用外部 api 并将其刷新到数据库中
【发布时间】:2020-09-16 21:56:29
【问题描述】:

我的 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');
  }    

}

即:

应用\员工

我还有一个以 JSON 获取请求形式出现的外部 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 之外,其他任何字段也可以从源中更改。

因为任何字段都可以随时更改。如何刷新整个数据库、保存新数据和更新更改?

谢谢

【问题讨论】:

  • 一种方法是清除表,并插入新记录。另一种方法是按 ID 检查所有本地记录,并检查其属性是否已从 API 更改。

标签: laravel guzzle


【解决方案1】:

我可以这样做:

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 存在则获取关联的模型。然后分配新值并保存您的模型。通过这种方式,您将能够在一个循环中创建或更新模型,而不会有任何复杂性。

【讨论】:

    【解决方案2】:

    不知道它是否有效,但你可以保留的逻辑..在另一个答案中,他在一个糟糕的循环下查询!

    希望对你有所帮助

    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);    
        }
    }
    

    让我知道它是否有用!

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 2021-06-24
      • 2015-12-04
      • 2017-05-17
      • 1970-01-01
      • 2018-03-08
      • 2021-02-27
      • 2015-04-25
      相关资源
      最近更新 更多