我使用的Vue与Laravel 5.6,我试图创建列表元素。 我的模板在下面,问题是我不能正确使用响应。对于此示例,我将退回一件商品,但在实际示例中,将有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\"}]
好了其他正常的数据则有不同的密钥,但要能prase这个我忽略了他们吧。
嗯,也是在我的模型我有
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);
}
}
答案 0 :(得分: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
];
});
}
答案 1 :(得分:0)
更好的方法可能是使用API Resoruces处理api的响应。 https://laravel.com/docs/5.7/eloquent-resources#generating-resources
在索引功能中
public function index()
{
return return YourResource::collection(YourModel::all());
}