我是 Laravel 5.4 和 Vue js 2 的新手,我遇到了这个我可以解决的问题。
我有一个带有 2 种方法(以及关联的路由)的 Controller :
public function index()
{
//
return BookingPayment::all();
}
public function index_booking($id_booking)
{
return BookingPayment::all()
->where('id_booking', '=', $id_booking)
->toArray(); // <<-- no effects !?
}
方法index
返回表中的所有行,index_booking
执行过滤器id_booking字段。
在 php 我的 PHP 页面中,我有一个 javascript,它对这两个路由执行请求。
我的问题是当我使用 index_booking
时,请求返回一个对象。我期望一个数组,因为我将能够轻松地使用数组函数来操作结果。
这是我的 JavaScript :
var vm = new Vue({
el: '#bookingpay',
data: function () {
return {
booking_id: 15,
payments: [],
input: [{id: 0, id_booking: 0, new_amount: 99}]
}
},
mounted: function () {
this.fetchPayment();
},
methods: {
fetchPayment: function () {
this.$http.get('/api/bookingpayments_bybooking/' + this.booking_id).then(function (response) {
this.payments = response.data;
})
},
delPayment: function (id, index) {
this.$http.delete('/api/bookingpayments/' + id).then(function () {
this.payments.splice(index, 1); // doesn't work on Ojbect
})
},
addPayment: function () {
this.$http.post('/api/bookingpayments', this.input).then(function () {
this.payments.push(this.input);
})
},
}
});
这是我期望的 http 查询响应格式。这就是我使用索引时所拥有的:
[
{
“ID”:79,
“id_booking”:3,
“金额”:“10.00”
},
{
“id”:80,
“id_booking”:3,
“金额”:“10.00”
},
....
这是我使用 index_booking
时得到的:
{
“28”:{
“ID”:29,
“id_booking”:15,
“金额”:“45.00”
},
“29”:{
“id”:30,
“id_booking”:15,
“金额”:“48.00”
}
}
我被困住了!任何帮助将不胜感激。干杯
最佳答案
您的index_booking
错误。正确的做法是:
public function index_booking($id_booking)
{
// This will return a Collection that will be translated to an array/json when you hit the endpoint via ajax. There is no need for toArray(), though...
return BookingPayment::where('id_booking', '=', $id_booking)->get();
}
关于javascript - Laravel 5/VueJS : Route for Get request route return Object or Array depending Eloquent query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45858857/