【问题标题】:Parsing Laravel response to proper JSON将 Laravel 响应解析为正确的 JSON
【发布时间】:2019-06-25 02:46:43
【问题描述】:

我正在使用带有 Laravel 5.6 的 Vue,并且我正在尝试创建一个列表元素。 我的模板在下面,问题是我无法正确使用响应。对于这个例子,我有一个项目返回,但在实际例子中会有 10 个项目的批次。需要一种将乱码转换为可读的普通 JSON 的方法

<template>
        <div>
            <tr v-for="row in list" v-bind:key='row.id'>
                <td align="left">{{row.list_type_id}}</td>

            </tr>
        </div>
    </template>

        <script>

        export default {
            name: 'List',
            data(){
                return{
                    list:{
                    }
                }
            },
            created() {
                this.getList()
            },
            methods:{
                getList(){
                    let self = this
                    $.ajax({
                        url: '/api/list',
                        success: function(result){
                            self.list = result;
                    }});
                }
            }
        }
        </script>

这是我从 Laravel 得到的回复;

[{"data":"{\"list_name\":\"STLTV2\",\"device_type_id\":\"6758\",\"entity_id\":\"1072\",\"client_id\":\"msx\"}]

通常,除了数据之外,还有不同的键,但为了能够表达这一点,我暂时忽略它们。

啊,我的模型里也有

protected $casts = [
    'data' => 'json'
];

在我只返回数据的地方添加我的控制器

public function index()
{
    return \DB::table('list_items')
        ->join('list', 'list_items.list_id', '=', 'list.id')
        ->where('list.type',3)
        ->limit(1)
        ->select(['data'])
        ->get();

}

因为我用limit(10 限制返回的记录,并且只选择data 列我可以使用 self.list = JSON.parse(result[0]['data']); 我希望能够转换data 以及其他字段

{
 'list_id': 1,
 'data': {
     'list_name':'STLTV2',
     ...
  }
}

添加 ListItem 模型

class ListItem extends Model
{

    protected $casts = [
        'data' => 'json'
    ];

    protected $fillable = [
        'list_id',
        'data',
    ];

    public function list()
    {
        return $this->belongsTo(Lists::class, 'list_id', 'id');
    }
}

添加列表模型

class Lists extends Model
{
    protected $casts = [
        'view' => 'json',
        'settings' => 'json'
    ];

    public function items()
    {
        return $this->hasMany(ListItem::class);
    }
}

【问题讨论】:

  • 你是如何输出你的 json 内容的?例如,显示一些关于您返回的响应类型的代码。
  • 你应该放 self.list 而不是 self.form,你不会在你的组件数据中形成变量。因此,请您与我们分享您的控制器吗?
  • 也添加了我的控制器。
  • @JerryLi 如我所料,你应该从控制器重组你的返回数据,在此之前你能和我们分享一下 list 和 list_items 表之间的关系吗?
  • 您应该使用Eloquent resources 来输出格式正确的 JSON 响应。

标签: json laravel vue.js


【解决方案1】:

要实现你想要的,你应该更新你的 index 方法,如下所示:

这里我们将使用Eloquent来选择我们的数据

public function index()
    {
        // here we get all listItems with list that has type = 3  
        $listItems = ListItem::with('lists' => function($query) {
            $query->where('type',3);
        })->get();

        return $listItems->map(function($item){

            return [
                'list_id' => $item->list_id,
                'list_item_id' => $item->list_item_id,

                 // put here all your data like key => value, and then you can get them from your vue component
                //'key' => value
            ];
        });
    }

【讨论】:

  • $listItems = ListItem::with(['list' =&gt; function($query) { $query-&gt;where('type',3); }])-&gt;get(); 需要 [] 但是当我使用 toSql() 时,我只会得到 select * from list_item ,仅此而已。这两个表的迁移没有联系,你认为是这个原因吗?
  • @JerryLi 您在 list_items 表中没有 list_id 外键吗?
  • $listItems =LisItem::whereHas('lists', function($q) { $q-&gt;where('type', '3'); })-&gt;get(); return $listItems; 这解决了我的问题。感谢您提醒@Thamer
【解决方案2】:

更好的方法可能是使用 API 资源来处理 api 的响应。 https://laravel.com/docs/5.7/eloquent-resources#generating-resources

在你的索引函数中

public function index()
{
    return return YourResource::collection(YourModel::all());

}

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 2021-09-24
    • 2017-05-24
    • 2016-04-27
    • 2016-01-09
    • 2013-09-19
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多