After doing a query, how can I create and echo a formatted JSON like this:

在进行查询后,如何创建和回显格式化的JSON,如下所示:

{
  "results": [
    {
      "user_id": "1",
      "name": "Apple",
      "address": "7538 N LA CHOLLA BLVD",
      "city": "Palo Alto",
      "state": "CA",
      "latlon": [
        -111.012654,
        32.339807
      ],
    },
    {
      "user_id": "2",
      "name": "Microsoft",
      "address": "75 S BWY STE 400",
      "city": "Palo Alto",
      "state": "CA",
      "latlon": [
        -73.764497,
        41.031858
      ],
    },
   ],

  "meta": {
    "page": 1,
    "per_page": 10,
    "count": 493,
    "total_pages": 50
  }
}

This is my current query:

这是我目前的查询:

public function getAgenciesJson() {

    $agencies = DB::table('users')->where('type','a')->orWhere('type','l');

}

Haven't figured out how to output JSON like that, considering I have a "latlon" field like [-111.012654,32.339807], also a "results" tag and a "meta" tag.

考虑到我有一个像[-111.012654,32.339807]这样的“latlon”字段,还有一个“结果”标签和一个“元”标签,所以还没想出如何输出这样的JSON。

Thanks in advance

提前致谢

3 个解决方案

#1


3

What you need is something called a transformer (or presenter) to convert your raw model into a format that can be sent to your users.

您需要的是一种称为变换器(或演示者)的东西,可将原始模型转换为可发送给用户的格式。

A very popular package is called Fractal (http://fractal.thephpleague.com/) by Phil Sturgeon. There's a Laravel package, that might make it a bit easier to use, called Larasponse (https://github.com/salebab/larasponse).

一个非常受欢迎的包被Phil Sturgeon称为Fractal(http://fractal.thephpleague.com/)。有一个Laravel软件包可能会让它更容易使用,称为Larasponse(https://github.com/salebab/larasponse)。

Phil actually a blog post about this just the other day - https://philsturgeon.uk/api/2015/05/30/serializing-api-output/ - that goes into why you should always have some kind of transformer between your models and what you send to your users.

菲尔实际上是关于这一天的博客文章 - https://philsturgeon.uk/api/2015/05/30/serializing-api-output/ - 这就是为什么你的模型之间应该总是有某种变换器以及您发送给用户的内容。

There's also a guide about using Larasponse and Fractal that might be of use here - http://laravelista.com/laravel-fractal/.

还有一个关于使用可能在这里使用的Larasponse和Fractal的指南 - http://laravelista.com/laravel-fractal/。

The gist of it boils down to passing the model through another class that will take the models values and build an array/object in a known/fixed format, e.g. (from Phil's blog post)

它的要点归结为将模型传递给另一个类,该类将获取模型值并以已知/固定格式构建数组/对象,例如, (来自Phil的博文)

return [
    'id'      => (int) $book->id,
    'title'   => $book->title,
    'year'    => (int) $book->yr,
    'author'  => [
        'name'  => $book->author_name,
        'email' => $book->author_email,
    ],
    'links'   => [
        [
            'rel' => 'self',
            'uri' => '/books/'.$book->id,
        ]
    ]
];

This way you're not exposing your original field names and if at any point your column names should change you only need to update that in 1 place rather than having to get any user of your JSON to update their site/app. It will also allow you to do string manipulation of your latlon column so that you can split it into 2 different values.

这样您就不会暴露原始字段名称,如果您的列名称在任何时候都应该更改,您只需要在一个位置更新它,而不是让任何JSON用户更新他们的站点/应用程序。它还允许您对latlon列进行字符串操作,以便将其拆分为2个不同的值。

Using a slightly modified example from the Fractal documentation. Say you have a transformer for a User

使用Fractal文档中稍加修改的示例。假设您有一个用户的变压器

class UserTransformer extends Fractal\TransformerAbstract
{
    public function transform(User $user) 
    {
        return [
            'id' => (int) $user->id,
            'name' => $user->first_name . ' ' . $user->last_name,
        ];
    }
}

You can then use this class to either transform a single item of a collection

然后,您可以使用此类来转换集合中的单个项目

$user = User::find(1);
$resource = new Fractal\Resource\Item($user, new UserTransformer);

// Or transform a collection
// $users = User::all();
// $resource = new Fractal\Resource\Collection($users, new UserTransformer);

// Use a manager to convert the data into an array or json
$json = (new League\Fractal\Manager)->createData($resource)->toJson();

Fractal includes a paginator adapter for Laravel that can be used straight away

Fractal包含Laravel的分页器适配器,可以立即使用

$paginator = User::paginate();
$users = $paginator->getCollection();

$resource = new Collection($users, new UserTransformer);
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));

更多相关文章

  1. 装机建项目vs2017和mysql5.7下建项目用EF建实体模型的过程..
  2. Netbeans6.1+JSF/VJSF/+JPA+MYSQL=酷炫快速开发模型
  3. Angular JS复选框 - 模型不默认为false
  4. three.js学习笔记 obj模型加载问题
  5. 如何在Sencha Touch中向模型添加自定义验证规则
  6. 在用户将'n'粘贴复制到文本字段后,如何更新视图模型?
  7. 如果外部应用程序更改了持久模型(服务器数据库),AngularJS可以自
  8. 获取Backbone Model实例的模型/类名
  9. 如何在v模型更改时触发事件? (vue js)

随机推荐

  1. Android Studio出错异常汇总
  2. Android Wear Preview- 为通知添加多个页
  3. 检查internet连接
  4. Android 控件的显示隐藏上下左右移动动画
  5. Android复制粘贴到剪贴板
  6. Android(安卓)API 28 使用 android-async
  7. Android Wear Preview- 从通知上接收语音
  8. Android 开源框架的收集
  9. 网络书签about Android
  10. Android UI详解之动态布局