获取json对象的数组并映射到模型类Laravel

时间:2019-01-21 03:33:10

标签: arrays json object model mapping

我打算将外部api的输出映射到模型中的object属性。

例如,data-> x到Device-> $ attribute_x; data-> y到Device-> $ attribute_y;输出是对象数组。

我的预期结果是通过访问Device模型及其属性来提取每个对象,并在模型中进行一些操作。 (仅从API提取一次,然后在其他函数中对其进行格式化)

有人可以提供一些有关定义方法/类的方法的指导吗?

这是我从外部API输出的结果:

{
    "data": [
        {
            "x": "1",
            "y": "2"
        },
        {
            "x": "11",
            "y": "22"
        }
    ]
}

这是Laravel中没有扩展Eloquent的模型,无法使用guzzle从外部API提取所有数据。

namespace App;

$client = new \GuzzleHttp\Client([
   'base_uri' => 'https://xxxx.com',
   'headers' => [
   'content_type' => 'application/json',
   'accept' => 'application/json'
   ]]);

$response = $client->get('units');
$data = json_decode($response->getBody());



class Devices
{
    protected $attribute_x;
    protected $attribute_y;

    public static function all(){

    }
}

1 个答案:

答案 0 :(得分:1)

我从头开始编写代码,但是您可以按照以下方法在设备中创建

componentWillMount() {
    console.log('componentWillMount');
    try {
        console.log('before');

        var userAgentApplication = new UserAgentApplication(applicationConfig.clientID, applicationConfig.authority, function (errorDesc, token, error, tokenType) {
            // Called after loginRedirect or acquireTokenPopup
            console.log('callback called');
        }, {cacheLocation: 'localStorage'});

        userAgentApplication.acquireTokenSilent(["user.read"], null, null, "&login_hint=first.last@mydomain.cp,&domain_hint=mydomain.com")
            .then(token => console.log('token', token))
            .catch((err) => console.log('err', err));

        userAgentApplication.acquireTokenSilent(["user.read"], "&login_hint=first.last@mydomain.cp,&domain_hint=mydomain.com")
            .then(token => console.log('token', token))
            .catch((err) => console.log('err', err));

        console.log('after');

    }
    catch (e) {
        console.log('caught error: ', e);
    }
}

并使用它从API json的数据数组中导入设备列表

public static function importFromAPI($data) {

    $result = [];

    foreach($data as $item) {
        $dev = new Device;
        $dev->attribute_x = $item['x'];
        $dev->attribute_y = $item['y'];
        $result[] = $dev;
    }

    return $result;
}

您的$devices = Devices::importFromAPI($data); 可以扩展雄辩的Device类,从而可以轻松访问数据库。上面的方法也可以在单独的类中实现,例如Model,并重命名为ApiService,并包含用于加载json并将其映射到Device对象的代码。