Reputation: 5
I have 3 tables (foods, orders and orderItems). I want to get orders of a user with orderItems and foods, but i failed.
Here's a result what i am getting right now, but i need to get food details instead of food_id.
[
{
"id": 16,
"user_id": 2,
"total": "12.50",
"items": [
{
"id": 20,
"order_id": 16,
"food_id": 1,
"quantity": 1,
"food_price": "12.50",
}
]
}
]
OrderController
$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items')->get());
User Model
public function deliveredOrders()
{
return $this->hasMany(Order::class)->where('status', '=', 'delivered');
}
Order Model
public function items()
{
return $this->hasMany(OrderItem::class);
}
Upvotes: 0
Views: 471
Reputation: 61
You should create this relationship in the OrderItem model
public function food()
{
return $this->belongsTo('App\Food'); //or wherever you have the model
}
and then get it
$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items.food')->get());
Upvotes: 1
Reputation: 840
You should define food() method on OrderItem model.
public function food()
{
return $this->belongsTo('App\Food');
}
And get relation data using this:
$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items.food')->get());
Upvotes: 0