Laravel - 如何解决外部API的特殊日期问题?

问题描述 投票:0回答:1

在我的Laravel-5.8项目中, 我有这样一个模型: 雇员

雇员

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

    protected $primaryKey = 'id';

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

}

就是说,。

App\Employee

 CREATE TABLE `employees` (
     `id` int NOT NULL auto_increment,
     `staff_code` varchar(255) UNIQUE NOT NULL,
     `first_name` varchar(255) UNIQUE NOT NULL,
     `last_name` varchar(255) NOT NULL,
     `date_of_birth` date NOT NULL

) ENGINE=MyISAM DEFAULT CHARSET=latin1;


Also I have an external api that comes in form of JSON get request.

https://api.employees.net/allemployees

我用邮递员的请求查看了它,我有这样的东西。

 {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DateOfBirth": "1992-07-11T00:00:00",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DateOfBirth": "1991-10-23T00:00:00",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DateOfBirth": "1979-09-22T00:00:00",
 },

以此类推... 继续

我已经创建了这个功能。

使用App/Employee;

 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->date_of_birth = $clientdata['DateOfBirth'];
        $employee->save();
     }
 }

从外部API传来的DateOfBirth带有一个特殊的字符(T),而数据库中的date_of_birth的数据类型是date. 而数据库中的date_of_birth的数据类型是date。

我想把来自外部API的数据保存到本地数据库中。

我如何将API中的DateOfBirth格式化为日期数据类型,并删除T00:00:00?

谢谢,谢谢

laravel guzzle
1个回答
1
投票

从这个字符串中提取你需要的东西。

$employee->date_of_birth = substr($clientdata['DateOfBirth'], 0,10);
© www.soinside.com 2019 - 2024. All rights reserved.